我在websocket中工作。而我從一個簡單的例子一個WebSocket的URL格式,我谷歌這樣的:下面
ws://{{$}}/ws
比較完整代碼:
home.html的:
<html>
<head>
<title>Chat Example</title>
<script type="text/javascript">
$(function() {
......
if (window["WebSocket"]) {
conn = new WebSocket("ws://{{$}}/ws");
conn.onclose = function(evt) {
appendLog($("<div><b>Connection closed.</b></div>"))
}
conn.onmessage = function(evt) {
appendLog($("<div/>").text(evt.data))
}
} else {
appendLog($("<div><b>Your browser does not support WebSockets.</b></div>"))
}
......
});
</script>
</head>
</html>
和wsServer.go:
package main
import (
"flag"
"log"
"net/http"
"text/template"
)
var addr = flag.String("addr", ":8080", "http service address")
var homeTempl = template.Must(template.ParseFiles("home.html"))
func serveHome(w http.ResponseWriter, r *http.Request) {
......
w.Header().Set("Content-Type", "text/html; charset=utf-8")
homeTempl.Execute(w, r.Host)
}
func main() {
http.HandleFunc("/", serveHome)
http.HandleFunc("/ws", serveWs)
err := http.ListenAndServe(:8080, nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
我認爲這將是一個正則表達式,而實際上我無法解釋它。
我測試它在我自己的電腦瀏覽器,並與連接成功:
http://localhost:8080
但
http://ip:8080 (which ip is my computer's also the litsening server's ip)
沒有。 爲什麼?
當然它工作時,我改變 「WS:// {{$}}/WS」 到一定的URL。但我想知道爲什麼?這個表達式匹配什麼?
完整的示例代碼是大,我覺得上面是不夠的問題。如果我錯過了一些東西,你可以在這個頁面找到完整的例子:https://github.com/garyburd/go-websocket/tree/master/examples/chat
請發表您的完整的例子。 http:// localhost:port working和http:// ip:port可能意味着你沒有使用正確的ip:port,你被防火牆,你綁定到localhost等。 –
@StephenWeinberg感謝您的提醒。我已經重新編輯並對我的帖子進行了修改。希望你現在很清楚。 – xsuii