1. 程式人生 > >go:搭建WebSocket服務端

go:搭建WebSocket服務端

原帖;http://www.jb51.net/article/110276.htm

//WebSoketDemo01

package main


import (
"fmt"
"log"
"net/http"
"golang.org/x/net/websocket"
)


func Echo(ws *websocket.Conn) {
var err error
for {
var reply string
if err = websocket.Message.Receive(ws, &reply); err != nil {
fmt.Println("can not receive")
break
}
fmt.Println("Received back from client:" + reply)


msg := "Received:" + reply
fmt.Println("Sending to client: " + msg)


if err = websocket.Message.Send(ws, msg); err != nil {
fmt.Println("can not send")
}
}
}


func main() {
http.Handle("/", websocket.Handler(Echo))
if err := http.ListenAndServe(":1234", nil); err != nil {
log.Fatal("ListenAndServe:", err)
}

}

使用:執行go run WebSoketDemo01.go

開啟chrome-》更多工具-》開發者工具-》然後選擇Console,輸入:

var wsServer = 'ws://localhost:1234';
var websocket = new WebSocket(wsServer);
websocket.onopen = function (evt) {
 console.log("Connected to WebSocket server.");
};
 
websocket.onclose = function (evt) {
 console.log("Disconnected");
};
 
websocket.onmessage = function (evt) {
 console.log('Retrieved data from server: ' + evt.data);
};
 
websocket.onerror = function (evt, e) {
 console.log('Error occured: ' + evt.data);
};
回車執行,如果輸出Connected to WebSocket server,表示連結成功。

繼續在Console輸入執行:websocket.send("我是b"),可以看到輸出:

Retrieved data from server: Received:我是b //服務端返回的內容,這裡是原樣返回