💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
> 经常项目中会用到聊天室或者游戏通讯以及服务端之间的长连接通讯,会用到websocket,以下做了一个简单的演示效果 [TOC] ## 服务端代码 (main.go) ~~~ package main import ( "fmt" "github.com/gorilla/websocket" "net/http" "time" ) var upgrade = websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }} func wsHandler(w http.ResponseWriter, r *http.Request) { var wsConn *websocket.Conn var err error var data []byte if wsConn, err = upgrade.Upgrade(w, r, nil); err != nil { return } go func() { for { if err = wsConn.WriteMessage(websocket.TextMessage, []byte("heartbeat")); err != nil { return } time.Sleep(1 * time.Second) } }() for { if _, message, err = wsConn.ReadMessage(); err != nil { wsConn.Close() fmt.Println("wsConn is closed") break } fmt.Println("response to client", message) if string(message) == "ping" { message = []byte("pong") } if err = wsConn.WriteMessage(websocket.TextMessage, message); err != nil { wsConn.Close() fmt.Println("wsConn2 is closed") break } } } func main() { //http标准库 http.HandleFunc("/ws", wsHandler) http.ListenAndServe("0.0.0.0:5555", nil) } ~~~ ## HTML代码 (client.html) ~~~ <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> window.addEventListener("load", function(evt) { var output = document.getElementById("output"); var input = document.getElementById("input"); var ws; var print = function(message) { var d = document.createElement("div"); d.innerHTML = message; output.appendChild(d); }; document.getElementById("open").onclick = function(evt) { if (ws) { return false; } ws = new WebSocket("ws://localhost:5555/ws"); ws.onopen = function(evt) { print("OPEN"); } ws.onclose = function(evt) { print("CLOSE"); ws = null; } ws.onmessage = function(evt) { print("RESPONSE: " + evt.data); } ws.onerror = function(evt) { print("ERROR: " + evt.data); } return false; }; document.getElementById("send").onclick = function(evt) { if (!ws) { return false; } print("SEND: " + input.value); ws.send(input.value); return false; }; document.getElementById("close").onclick = function(evt) { if (!ws) { return false; } ws.close(); return false; }; }); </script> </head> <body> <table> <tr><td valign="top" width="50%"> <form> <button id="open">Open</button> <button id="close">Close</button> <input id="input" type="text" value="Hello world!"> <button id="send">Send</button> </form> </td><td valign="top" width="50%"> <div id="output"></div> </td></tr></table> </body> </html> ~~~ > 本程序代码简化自 > channel线程安全封装方式 > https://www.iteye.com/blog/wangking0717-2518522 > http://www.topgoer.com/%E5%85%B6%E4%BB%96/%E5%B0%81%E8%A3%85websocket.html > beego websocket: > https://blog.csdn.net/u012210379/article/details/72912056