我有一个简单的go web服务器,它服务于端口localhost:8080一个公共文件夹,包含一个html文件以及一个带有websocket逻辑的客户端脚本。
中listener, err := net.listen("tcp", "localhost:8080")
if err != nil {
log.Fatal(err)
}
//full code in gist https://gist.github.com/Kielan/98706aaf5dc0be9d6fbe
然后在我的客户端脚本中
try {
var sock = new WebSocket("ws://127.0.0.1:8080");
console.log("Websocket - status: " + sock.readyState);
sock.onopen = function(message) {
console.log("CONNECTION opened..." + this.readyState);
//onmessage, onerr, onclose, ect...
}
我在Chrome中遇到错误
WebSocket connection to 'ws://127.0.0.1:8080/' failed: Error during WebSocket handshake: Unexpected response code: 200
和Firefox
Firefox can't establish a connection to the server at ws://127.0.0.1:8080/.
我发现this article引用node.js表示将/ websocket添加到我的客户端websocket字符串,虽然它没有解决问题并导致404
我认为响应代码200很好,我是否需要以某种方式将请求转换为websocket并且可能是默认为http?如果是这样我怎么能这样做?
答案 0 :(得分:1)
就像JimB指出的那样,你还没有处理http和websocket连接。
您可以使用包github.com/gorilla/websocket
进行websocket处理
这就是简单设置的样子:
package main
import (
"log"
"net/http"
"github.com/gorilla/websocket"
)
// wsHandler implements the Handler Interface
type wsHandler struct{}
func main() {
router := http.NewServeMux()
router.Handle("/", http.FileServer(http.Dir("./webroot"))) //handles static html / css etc. under ./webroot
router.Handle("/ws", wsHandler{}) //handels websocket connections
//serving
log.Fatal(http.ListenAndServe("localhost:8080", router))
}
func (wsh wsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// upgrader is needed to upgrade the HTTP Connection to a websocket Connection
upgrader := &websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
//Upgrading HTTP Connection to websocket connection
wsConn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("error upgrading %s", err)
return
}
//handle your websockets with wsConn
}
在您的Javascript中,您显然需要var sock = new WebSocket("ws://localhost/ws:8080");
。