[Go] 实现websocket服务端
直接使用官方子包可以实现websocket协议,
golang.org/x/net/websocket
如果在这个目录没有这个包就去github下载net库,放进这个目录$GOPATH/src/golang.org/x/net就行了
服务端代码:
package main import ( "time" "log" "net/http" "golang.org/x/net/websocket" ) func main(){ http.HandleFunc("/",index) http.Handle("/websocket",websocket.Handler(instantMessage)) log.Println("start server") err:=http.ListenAndServe(":1234",nil) log.Println(err) } func index(res http.ResponseWriter,req *http.Request){ res.Write([]byte("hello world")) } func instantMessage(w *websocket.Conn) { var error error for { var reply string if error= websocket.Message.Receive(w,&reply);error!=nil{ log.Println("接受消息失败",error) break } log.Println("客户端:",reply) msg:="服务端:"+reply+time.Now().String() log.Println(msg) if error = websocket.Message.Send(w, msg); error != nil { log.Println("发送消息失败") break } } }
客户端代码:
<html> <head> <title>好好学习</title> </head> <body> <script type="text/javascript"> var sock = null; // var wsuri = "wss://127.0.0.1:8080"; //本地的地址 是可以改变的哦 var wsuri = "ws://localhost:1234/websocket"; //本地的地址 是可以改变的哦 window.onload = function() { //可以看到客户端JS,很容易的就通过WebSocket函数建立了一个与服务器的连接sock,当握手成功后,会触发WebScoket对象的onopen事件,告诉客户端连接已经成功建立。客户端一共绑定了四个事件。 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); document.getElementById(‘receive‘).innerHTML=e.data; } //发生错误的时候触发 sock.onerror=function (e) { console.log("发生错误时候触发"+wsuri) } }; //如果sock被关闭掉了 这里 也会报错的啊 function send() { var msg = document.getElementById(‘message‘).value; sock.send(msg); }; </script> <h1>客户端</h1> <form> <p>发送: </p> <textarea id="message" >我是陶士涵</textarea> <p>接收: </p> <textarea id="receive" ></textarea> </form> <button onclick="send();">给服务器发送消息</button> </body> </html>
相关推荐
柳木木的IT 2020-11-04
joynet00 2020-09-23
wenf00 2020-09-14
蓝色深海 2020-08-16
wuychn 2020-08-16
取个好名字真难 2020-08-06
darylove 2020-06-26
shufen0 2020-06-20
Lovexinyang 2020-06-14
WangBowen 2020-06-14
firejq 2020-06-14
hjhmpl 2020-06-14
水痕 2020-06-07
guozewei0 2020-06-06
woniyu 2020-06-02
取个好名字真难 2020-06-01
guozewei0 2020-05-28
woniyu 2020-05-26