golang websocket 单聊
时间: 2023-11-18 15:06:05 浏览: 103
使用Golang可以很方便地实现WebSocket单聊功能。下面是一个简单的示例代码:
```go
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func main() {
http.HandleFunc("/ws", handleWebSocket)
err := http.ListenAndServe(":1234", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
func handleWebSocket(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println("upgrade:", err)
return
}
defer conn.Close()
for {
// 读取客户端发送的消息
_, message, err := conn.ReadMessage()
if err != nil {
log.Println("read:", err)
break
}
log.Printf("recv: %s", message)
// 发送消息给客户端
err = conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf("你发送了: %s", message)))
if err != nil {
log.Println("write:", err)
break
}
}
}
```
这个示例代码实现了一个简单的WebSocket单聊功能,当客户端连接到服务器时,服务器会不断地读取客户端发送的消息,并将消息发送回客户端。
阅读全文