我有一个简单的go web服务器,它服务于端口localhost:8080,这是一个包含html文件和带有websocket逻辑的客户端脚本的公用文件夹。
在我的main.go文件里
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...
}我得到了铬的错误
WebSocket connection to 'ws://127.0.0.1:8080/' failed: Error during WebSocket handshake: Unexpected response code: 200和火狐
Firefox can't establish a connection to the server at ws://127.0.0.1:8080/.我发现这篇文章引用了node.js,指示要将/websocket添加到我的客户端websocket字符串中,尽管它没有解决问题,导致了404。
我认为响应代码200很好,我是否需要以某种方式将请求转换为websocket,并且它可能默认为http?如果是这样的话,我该怎么做呢?
发布于 2016-02-04 14:31:06
正如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");。
https://stackoverflow.com/questions/35202405
复制相似问题