Go語言標准包里面沒有提供對WebSocket的支持,但是在由官方維護的go.net子包中有對這個的支持,需要獨立下載, Go websocket package 下載地址:http://code.google.com/p/go.net/websocket 。
Go get 命令下載:go get code.google.com/p/go.net/websocket
Go實現的WebSocket的文檔:http://godoc.org/code.google.com/p/go.net/websocket
WebSocket官網提供了一個webSocket測試地址: http://www.websocket.org/echo.html 在這里輸入 websocket的地址就可以進行測試。
Go服務器端源碼:
package main
import (
"code.google.com/p/go.net/websocket"
"fmt"
"log"
"net/http"
)
func Echo(ws *websocket.Conn) {
var err error
for {
var reply string
if err = websocket.Message.Receive(ws, &reply); err != nil {
fmt.Println("Can't 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't send")
break
}
}
}
func main() {
fmt.Println("begin")
http.Handle("/", http.FileServer(http.Dir("."))) // <-- note this line
http.Handle("/socket", websocket.Handler(Echo))
if err := http.ListenAndServe(":1234", nil); err != nil {
log.Fatal("ListenAndServe:", err)
}
fmt.Println("end")
}
測試的網頁:
<!DOCTYPE html>
<meta charset="utf-8" />
<title>WebSocket Test</title>
<script language="javascript"type="text/javascript">
var wsUri ="ws://localhost:1234/socket";
//var wsUri = "ws://localhost/socket";
//var wsUri = "ws://echo.websocket.org";
var output;
function init() {
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket() { websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) }; }
function onOpen(evt) { writeToScreen("CONNECTED"); doSend("WebSocket rocks"); } function onClose(evt) {
writeToScreen("DISCONNECTED"); }
function onMessage(evt) {
writeToScreen('<span style="color: blue;">RESPONSE: '+ evt.data+'</span>');
websocket.close(); }
function onError(evt) {
writeToScreen('<span style="color: red;">ERROR:</span> '+ evt.data); }
function doSend(message) {
writeToScreen("SENT: " + message);
websocket.send(message); }
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message; output.appendChild(pre); }
window.addEventListener("load", init, false);
</script>
<h2>WebSocket Test</h2>
<div id="output"></div>
</html>
注意,測試時候 測試html網頁是需要在 http://localhost:1234/test.html 這樣的地址進行測試。
如果用 file://localhost/Users/cybercare/go/src/websocket/test.html 測試會報錯誤。
Chrome瀏覽器可能會拋出400錯誤,是因為它認為你正在嘗試做一個跨域請求WebSocket。即它認為你沒有跨域請求的權限。You should host your html+javascript on http:// (or https://), not file://
Static html page created the WebSocket connection golang server directly
http://stackoverflow.com/questions/15884480/static-html-page-created-the-websocket-connection-golang-server-directly
Go websocket server not working with browser
https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/pNYy5brIF6E
不過如果使用 file://localhost/Users/cybercare/go/src/websocket/test.html 訪問訪問
var wsUri = "ws://echo.websocket.org"; 則不會有任何問題,而訪問 var wsUri = "ws://localhost:1234/socket"; 就會報上面錯誤:
使用
打開 chrome://net-internals/#events, 輸入ws進行過濾,其中的 SOCKET_STREAM 信息如下:
下面是本地靜態文件請求 ws://echo.websocket.org/ 的信息截屏。
Websockets?
https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/2QwiBb7ZgrA
本地靜態文件請求 ws://localhost:1234/socket 提示錯誤: HTTP/1.1 400 Bad Request 的信息監控。
這是因為 我們用的這個 websocket 框架 在處理請求的 Origin 時,把它當URL來處理,而本地靜態文件發送上來的Origin是null。這里解析錯誤就會報400錯誤。
go 官方的這個Orgin解析代碼我們可以在下面地址看到(536行):
https://code.google.com/p/go/source/browse/websocket/hixie.go?repo=net#536
參考資料
go-websocket-sample
https://github.com/ukai/go-websocket-sample
Can't connect to Server through Chrome.
https://code.google.com/p/go/issues/detail?id=3987
Go WebSocket開發
http://www.cnblogs.com/yjf512/archive/2013/02/18/2915171.html
8.2 WebSocket
https://github.com/astaxie/build-web-application-with-golang/blob/master/ebook/08.2.md
廣泛意思上的websocket包
http://bbs.mygolang.com/thread-330-1-1.html
golang websocket總結(問題貼)
http://blog.csdn.net/lxy15329/article/details/8737912
基於Golang的WebSocket Server
http://www.xinze.me/%E5%9F%BA%E4%BA%8Egolang%E7%9A%84websocket-server/