go语言实现一个webSocket的一个demo
前端代码
<html lang="zh-CN">
<head></head>
<body>
<script type="text/javascript">
// header('Access-Control-Allow-Origin:*');
var sock = null;
var wsuri = "ws://127.0.0.1:9999";
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>
服务端
package main
import (
"fmt"
"golang.org/x/net/websocket"
"log"
"net/http"
)
func main() {
http.Handle("/", websocket.Handler(Echo)) //这里校验请求头的Origin字段
if err := http.ListenAndServe("127.0.0.1:9999", nil); err != nil {
log.Fatal("ListenAndServer: ", err)
}
}
func Echo(ws *websocket.Conn) {
var err error
for {
var reply string
err = websocket.Message.Receive(ws, &reply)
if err != nil {
fmt.Println("Can't receive data...")
break
}
fmt.Println("Receive back from client:" + reply)
msg := "Receive: " + "接受到客户端的消息,ok"
fmt.Println("Sending to client: " + msg)
err = websocket.Message.Send(ws, msg)
if err != nil {
fmt.Println("发送消息失败")
break
}
}
}