https://github.com/Allenxuxu/gev
gev 是一个轻量、快速、高性能的基于 Reactor 模式的非阻塞网络库,底层并不使用 golang net 库,而是使用 epoll 和 kqueue。
现在它支持 WebSocket 啦!
支持定时任务,延时任务!
⬇️⬇️⬇️
测试环境 Ubuntu18.04
限制 GOMAXPROCS=1,1 个 work 协程
限制 GOMAXPROCS=1,4 个 work 协程
限制 GOMAXPROCS=4,4 个 work 协程
go get -u github.com/Allenxuxu/gev
package main
import (
	"flag"
	"strconv"
	"log"
	"github.com/Allenxuxu/gev"
	"github.com/Allenxuxu/gev/connection"
	"github.com/Allenxuxu/ringbuffer"
)
type example struct{}
func (s *example) OnConnect(c *connection.Connection) {
	log.Println(" OnConnect: ", c.PeerAddr())
}
func (s *example) OnMessage(c *connection.Connection, buffer *ringbuffer.RingBuffer) (out []byte) {
	//log.Println("OnMessage")
	first, end := buffer.PeekAll()
	out = first
	if len(end) > 0 {
		out = append(out, end...)
	}
	buffer.RetrieveAll()
	return
}
func (s *example) OnClose() {
	log.Println("OnClose")
}
func main() {
	handler := new(example)
	var port int
	var loops int
	flag.IntVar(&port, "port", 1833, "server port")
	flag.IntVar(&loops, "loops", -1, "num loops")
	flag.Parse()
	s, err := gev.NewServer(handler,
		gev.Network("tcp"),
		gev.Address(":"+strconv.Itoa(port)),
		gev.NumLoops(loops))
	if err != nil {
		panic(err)
	}
	s.Start()
}
package main
import (
	"flag"
	"github.com/Allenxuxu/gev/ws"
	"log"
	"math/rand"
	"strconv"
	"github.com/Allenxuxu/gev"
	"github.com/Allenxuxu/gev/connection"
)
type example struct{}
func (s *example) OnConnect(c *connection.Connection) {
	log.Println(" OnConnect: ", c.PeerAddr())
}
func (s *example) OnMessage(c *connection.Connection, data []byte) (messageType ws.MessageType, out []byte) {
	log.Println("OnMessage:", string(data))
	messageType = ws.MessageBinary
	switch rand.Int() % 3 {
	case 0:
		out = data
	case 1:
		if err := c.SendWebsocketData(ws.MessageText, data); err != nil {
			if e := c.CloseWebsocket(err.Error()); e != nil {
				panic(e)
			}
		}
	case 2:
		if e := c.CloseWebsocket("close"); e != nil {
			panic(e)
		}
	}
	return
}
func (s *example) OnClose(c *connection.Connection) {
	log.Println("OnClose")
}
func main() {
	handler := new(example)
	var port int
	var loops int
	flag.IntVar(&port, "port", 1833, "server port")
	flag.IntVar(&loops, "loops", -1, "num loops")
	flag.Parse()
	s, err := gev.NewWebSocketServer(handler,
		gev.Network("tcp"),
		gev.Address(":"+strconv.Itoa(port)),
		gev.NumLoops(loops))
	if err != nil {
		panic(err)
	}
	s.Start()
}
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.