获得相应包支持:go get golang.org/x/net/websocket
package main
import (
"log"
"net/http"
"os"
"golang.org/x/net/websocket"
)
func main() {
log.Println(os.Args[0]) //第一个参数,显示文件路径
http.Handle("/", websocket.Handler(Echo))
if err := http.ListenAndServe(":8088", nil); err != nil {
log.Println(err)
}
}
func Echo(ws *websocket.Conn) {
for {
var raply string
if err := websocket.Message.Receive(ws, &raply); err != nil { //get infomation,write in adress
log.Println("can't receive")
break
}
msg := "Received:" + raply
log.Println(msg)
if err := websocket.Message.Send(ws, "come back infomation"); err != nil { //send infomation
log.Println("can't send")
break
}
}
}
解释:
(1)http.Handle("/", websocket.Handler(Echo))
主函数中的handle函数,将路由和相关的方法联系起来,不过要经过转化
(2)func Echo(ws *websocket.Conn)
这个函数中实现了逻辑的实行,for循环一直处理用户请求
其中: websocket.Message.Receive(ws, &raply)实现了数据的接收,存入对应的内存地址。
websocket.Message.Send(ws, "come back infomation")发送相应的数据,前台可以接收这个数据。
以下是前台模拟
192.168.149.1是我自己电脑的IP,根据自己的IP不同,提交的地址不一样,在这里改成自己的IP地址或者想要提交的服务器地址即可
<html>
<head>
<title></title>
</head>
<body>
<script>
var sock=null
var wxurl="ws://192.168.149.1:8088"
window.onload=function(){
sock= new WebSocket(wxurl)
sock.onopen = function(){
console.log("connect to "+wxurl)
}
sock.onmessage = function(e){
console.log("message:"+e.data)
alert(e.data)
$("#cs").text(e.data)
}
sock.onclose = function(e){
console.log("close:"+e.code)
}
}
function send(){
var msg = document.getElementById("ms").value
sock.send(msg)
}
</script>
<form>
<input id="ms" type="text" value="hello word" >
<label id="cs"></label>
</form>
<button onclick="send()" >push</button>
</body>
</html>
有疑问加站长微信联系(非本文作者)