首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往
您找到你想要的搜索结果了吗?
是的
没有找到

go实现websocket功能

package main import ( "fmt" "golang.org/x/net/websocket" //go get golang.org/x/net/websocket 下载websocket包 "html/template" //支持模板html "log" "net/http" ) func Echo(ws *websocket.Conn) { var err error for { var reply string //websocket接受信息 if err = websocket.Message.Receive(ws, &reply); err != nil { fmt.Println("can't receive") break } fmt.Println("reveived back from client: " + reply) msg := "received:" + reply fmt.Println("send to client:" + msg) //这里是发送消息 if err = websocket.Message.Send(ws, msg); err != nil { fmt.Println("can't send") break } } } func web(w http.ResponseWriter, r *http.Request) { //打印请求的方法 fmt.Println("method", r.Method) if r.Method == "GET" { //如果请求方法为get显示login.html,并相应给前端 t, _ := template.ParseFiles("websocket.html") t.Execute(w, nil) } else { //否则走打印输出post接受的参数username和password fmt.Println(r.PostFormValue("username")) fmt.Println(r.PostFormValue("password")) } } func main() { //接受websocket的路由地址 http.Handle("/websocket", websocket.Handler(Echo)) //打开html页面 http.HandleFunc("/web", web) if err := http.ListenAndServe(":1234", nil); err != nil { log.Fatal("ListenAndServe:", err) } } -------------------------------------------------- <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>go测试socket</title> </head> <body> <script type="text/javascript"> var sock = null; var wsuri = "ws://127.0.0.1:1234/websocket"; window.onload = function() { console.log("onload"); sock = new WebSocket(wsuri); sock.onopen = function() { console.log("connected to " + wsuri); } sock.onclose = function(e) { console.log("connection closed (" + e.code + ")");

03
领券