1 Star 1 Fork 0

hXoreyer / knet

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
MIT

Knet TCP框架

基于Golang的轻量级并发TCP框架

中文文档

实例:

server:

package main

import (
	"fmt"
	"net"
	"time"

	"github.com/hxoreyer/knet"
)

func main() {
	logger := knet.NewKlog("./logger")
	logger.SetUpdateTime("01:00:00") //日志文件更换时间设置,默认为"00:00:00"

	//日志三种格式,分别在success.log,info.log,error.log文件里
	logger.Success("Create logger success!!!")
	logger.Info("INFO INFO INFO!!!")
	logger.Error("Create logger error!!!")

	s := knet.NewTCPServer("127.0.0.1", 5555)
	//设置最大连接数
	s.SetMaxCon(1)

	//设置工作池数量
	s.SetWorkPoolSize(10)

	//全局中间件
	s.Use(func(request knet.IRequest) {
		fmt.Println("[Middleware] This is middleware1, Id:", request.GetID())
	})
	s.Use(func(request knet.IRequest) {
		fmt.Println("[Middleware] This is middleware2, Id:", request.GetID())
		if string(request.GetData()) == "hxoreyer" {
			fmt.Println("[Middleware] Abort from middleware2")
			s.Abort()
		}
	})

	//请求路由
	s.Before(1, func(request knet.IRequest) {
		fmt.Printf("[Router] Recv Before, ID = %d\n", request.GetID())
	})

	s.On(1, func(request knet.IRequest) {
		fmt.Printf("[Router] Recv from %s, ID = %d Data = %s\n", request.GetConnection().RemoteAddr().String(), request.GetID(), request.GetData())
		request.GetConnection().Send(request.GetID(), request.GetData())
	})
	s.On(2, func(request knet.IRequest) {
		fmt.Printf("[Router] Recv from %s, ID = %d Data = %s\n", request.GetConnection().RemoteAddr().String(), request.GetID(), request.GetData())
		request.GetConnection().Send(request.GetID(), request.GetData())
	})

	s.After(2, func(request knet.IRequest) {
		fmt.Printf("[Router] Recv After, ID = %d\n", request.GetID())
	})

	//超出最大连接数
	s.OverLoad(func(c *net.TCPConn) {
		dp := knet.NewPack()

		msg1 := &knet.Message{
			Id:      9,
			DataLen: 8,
			Data:    []byte("overload"),
		}
		buf, _ := dp.Pack(msg1)
		c.Write(buf)
		time.Sleep(time.Millisecond)
	})
	//连接开始时
	s.OnStart(func(c knet.IConnection) {
		c.SetProperty("name", "keing")
	})
	//连接结束时
	s.OnStop(func(c knet.IConnection) {
		fmt.Println(c.GetProperty("name"))
	})
	s.Run()
}

client:

package main

import (
	"fmt"
	"io"
	"net"
	"time"

	"github.com/hxoreyer/knet"
)

var exit = false

func main() {
	con, err := net.Dial("tcp", ":5555")
	if err != nil {
		fmt.Println("dail err:", err)
		return
	}
	go Reader(con)
	dp := knet.NewPack()

	msg1 := &knet.Message{
		Id:      1,
		DataLen: 5,
		Data:    []byte("keing"),
	}
	buf, _ := dp.Pack(msg1)

	msg2 := &knet.Message{
		Id:      2,
		DataLen: 8,
		Data:    []byte("hxoreyer"),
	}
	buf2, _ := dp.Pack(msg2)
	buf = append(buf, buf2...)
	for {
		con.Write(buf)
		time.Sleep(time.Second)
		if exit {
			break
		}
	}
}

func Reader(con net.Conn) {
	for {
		dp := knet.NewPack()
		head := make([]byte, dp.GetHeadLen())
		if _, err := io.ReadFull(con, head); err != nil {
			fmt.Println("read msg head err:", err)
			exit = true
			break
		}

		msg, err := dp.Unpack(head)
		if err != nil {
			fmt.Println("unpack err:", err)
			break
		}

		if msg.GetLen() > 0 {
			temp := make([]byte, msg.GetLen())
			if _, err := io.ReadFull(con, temp); err != nil {
				fmt.Println("read msg data err:", err)
				break
			}
			msg.SetData(temp)
		}
		fmt.Printf("[Recv] ID = %d, Data = %s\n", msg.GetID(), string(msg.GetData()))
	}
}
MIT License Copyright (c) 2021 hXoreyer Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

简介

基于Golang的轻量级TCP服务器框架 展开 收起
Go
MIT
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Go
1
https://gitee.com/hXoreyer/knet.git
git@gitee.com:hXoreyer/knet.git
hXoreyer
knet
knet
master

搜索帮助

53164aa7 5694891 3bd8fe86 5694891