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 ")"); } sock.onmessage = function(e) { console.log("message received: " e.data); } }; function send() { var msg = document.getElementById('message').value; sock.send(msg); }; </script> <h1>WebSocket Echo Test</h1> <form> <p> Message: <input id="message" type="text" value="Hello, world!"> </p> </form> <button onclick="send();">Send Message</button> </body> </html>
go实现websocket功能
2022-04-25 08:24:29
浏览数 (1)