golang开发 gorilla websocket的使用
|
很多APP都需要主动向用户推送消息,这就需要用到长连接的服务,即我们通常提到的websocket,同样也是使用socket服务,通信协议是基本类似的,在go中用的最多的、也是最简单的socket服务就是gorilla/websocket,它有21.1K的star,足以说明它的受欢迎程度, 它的github地址是 https://github.com/gorilla/websocket,我们的长连接服务也是通过gorilla/websocket改造出来的。
websocket的简单使用
我们使用的版本是1.3.0,首先下载websocket
go get github.com/gorilla/websocket@v1.3.0
把websocket/examples/echo下面的 client.go server.go 现在下来拷贝到项目里面。
https://github.com/gorilla/websocket/blob/v1.3.0/examples/echo/server.go
https://github.com/gorilla/websocket/blob/v1.3.0/examples/echo/client.go
在一个终端执行 websocket 服务
go run server.go- recv: 2024-04-16 15:09:45.805438 +0800 CST m=+1.007536889
- recv: 2024-04-16 15:09:46.805425 +0800 CST m=+2.007517605
- recv: 2024-04-16 15:09:47.806274 +0800 CST m=+3.008359325
- recv: 2024-04-16 15:09:48.80495 +0800 CST m=+4.007028866
- recv: 2024-04-16 15:09:49.805743 +0800 CST m=+5.007816108
- recv: 2024-04-16 15:09:50.806087 +0800 CST m=+6.008153310
- recv: 2024-04-16 15:09:51.805348 +0800 CST m=+7.007407266
复制代码 再打开一个终端执行 go run client.go,充当客户端- connecting to ws://localhost:8080/echorecv: 2024-04-16 15:09:45.805438 +0800 CST m=+1.007536889
- recv: 2024-04-16 15:09:46.805425 +0800 CST m=+2.007517605
- recv: 2024-04-16 15:09:47.806274 +0800 CST m=+3.008359325
- recv: 2024-04-16 15:09:48.80495 +0800 CST m=+4.007028866
- recv: 2024-04-16 15:09:49.805743 +0800 CST m=+5.007816108
- recv: 2024-04-16 15:09:50.806087 +0800 CST m=+6.008153310
- recv: 2024-04-16 15:09:51.805348 +0800 CST m=+7.007407266
复制代码 我们看看这个简单的例子。
client.go
[code]go func() { defer close(done) for { _, message, err := c.ReadMessage() if err != nil { log.Println("read:", err) return } log.Printf("recv: %s", message) } }() ticker := time.NewTicker(time.Second) defer ticker.Stop() for { select { case |
|
|
|
发表于 2024-5-30 17:25:47
举报
回复
分享
|
|
|
|