- 有的時(shí)候我們會(huì)用到websocks來處理一些即時(shí)的Web事物,比如像聊天室之類,Go語言的websocks運(yùn)用起來還是很簡(jiǎn)單的,有一個(gè)現(xiàn)成的包gobwas,本文化繁為簡(jiǎn),砍掉絕大部分高階用法,中間也填了幾個(gè)不算很深的坑,此代碼復(fù)制粘貼后可運(yùn)行。
package main
import (
"fmt"
"github.com/gobwas/ws" //Websocks工具
"github.com/gobwas/ws/wsutil"
"net"
"net/http"
)
var conn net.Conn //全局conn
func main() {
var httpSrv *http.Server
httpSrv = &http.Server{Addr: ":8082"}
http.HandleFunc("/", wss)
httpSrv.ListenAndServe()
}
func startWsServer(w http.ResponseWriter, r *http.Request) net.Conn {
conn, _, _, _ = ws.UpgradeHTTP(r, w)
return conn
}
func wss(w http.ResponseWriter, r *http.Request) {
if conn != nil {
fmt.Println("old conn killed:", conn)
conn.Close()
}
//此處不能直接初始化conn,而是需要用一個(gè)函數(shù)來初始化conn,否則數(shù)據(jù)交換太快了會(huì)卡頓,原因未知
conn := startWsServer(w, r)
fmt.Println("new conn creative:", conn)
for {
msg_receive, _, _ := wsutil.ReadClientData(conn)
str_receive := string(msg_receive)
if str_receive != "" {
fmt.Println("msg_receive: ", str_receive) //接收到客戶端的內(nèi)容
if str_receive == "123" { //如果客戶端發(fā)來"123",則回傳"Hello World!"
sm("Hello World!")
}
}
}
}
func sm(cmds string) {
var msg_send []byte = []byte(cmds)
wsutil.WriteServerMessage(conn, ws.OpText, msg_send)
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。