好的,这是一个简单的 websocket 通信程序的示例代码: ``` package main import ( "bufio" "fmt" "net/http" "github.com/gorilla/websocket" ) var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, } func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { fmt.Println("Failed to set websocket upgrade: %+v", err) return } for { messageType, p, err := conn.ReadMessage() if err != nil { break } if err := conn.WriteMessage(messageType, p); err != nil { break } } }) err := http.ListenAndServe(":8080", nil) if err != nil { fmt.Println("Failed to set websocket upgrade: %+v", err) } } ``` 代码实现了一个简单的 websocket 通信服务器,当客户端连接到服务器时,服务器将发送的消息返回给客户端。 该代码使用了 gorilla/websocket 库,因此在编译前需要安装该库。你可以在命令行中输入以下命令安装: ``` go get -u github.com/gorilla/websocket ```