golang使用websocket
时间: 2023-11-09 15:58:39 浏览: 133
golang websocket
要在Golang中使用WebSocket,你可以使用`github.com/gorilla/websocket`包。首先,你需要安装该包:
```
go get github.com/gorilla/websocket
```
然后,你可以使用以下代码示例创建WebSocket服务器和客户端:
```go
// 服务器端
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/websocket"
)
// 处理WebSocket连接
func handleWebSocket(w http.ResponseWriter, r *http.Request) {
// 升级HTTP连接为WebSocket协议
conn, err := websocket.Upgrade(w, r, nil, 1024, 1024)
if err != nil {
log.Println(err)
return
}
defer conn.Close()
// 在这里处理WebSocket消息
for {
// 读取客户端发送的消息
_, msg, err := conn.ReadMessage()
if err != nil {
log.Println(err)
break
}
fmt.Println(string(msg))
// 发送消息给客户端
if err := conn.WriteMessage(websocket.TextMessage, []byte("Hello from server")); err != nil {
log.Println(err)
break
}
}
}
func main() {
http.HandleFunc("/", handleWebSocket)
log.Fatal(http.ListenAndServe(":8080", nil))
}
// 客户端
package main
import (
"fmt"
"log"
"net/url"
"os"
"os/signal"
"time"
"github.com/gorilla/websocket"
)
func main() {
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
u := url.URL{Scheme: "ws", Host: "localhost:8080", Path: "/"}
log.Printf("connecting to %s", u.String())
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
log.Fatal("dial:", err)
}
defer c.Close()
done := make(chan struct{})
// 接收和处理服务端发送的消息
go func() {
defer close(done)
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
return
}
fmt.Printf("received: %s\n", message)
}
}()
// 定期向服务端发送消息
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-done:
return
case t := <-ticker.C:
err := c.WriteMessage(websocket.TextMessage, []byte(t.String()))
if err != nil {
log.Println("write:", err)
return
}
case <-interrupt:
log.Println("interrupt")
err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
log.Println("write close:", err)
return
}
select {
case <-done:
case <-time.After(time.Second):
}
return
}
}
}
```
这是一个简单的示例,服务器接收客户端的消息并将其打印出来,然后向客户端发送"Hello from server"的消息。客户端定期向服务器发送当前时间。
阅读全文