[TOC] ## 安装 ``` go get github.com/gorilla/websocket ``` ## simple ``` var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, // 启用压缩,试验特性 EnableCompression: true, } func handler(w http.ResponseWriter, r *http.Request) { // 升级为WebSocket协议 conn, _ := upgrader.Upgrade(w, r, nil) for { // 回响服务 // 消息类型可以是websocket.BinaryMessage、websocket.TextMessage messageType, p, _ := conn.ReadMessage() conn.WriteMessage(messageType, p) // 也可以使用io.WriteCloser、io.Reader来收发消息 messageType, reader, _ := conn.NextReader() writer, _ := conn.NextWriter(messageType) io.Copy(writer, reader) // 一直读取到EOF writer.Close() } } ```