按 TCP 或者 HTTP, 两个服务监听同一端口是会报错的,
但 Socket.IO 却可以直接监听 Express 服务器的同一端口,
具体原因是什么?
WebSockets 是基于 HTTP 实现, 是否相关?
怪我咯2017-04-17 11:08:14
It should be that two programs monitoring one port will report an error.
Websocket and http are all implemented based on tcp. Websocket connection requests all use http. Websocket and http are on the same level. For example, handling websocket requests in Go:
Route:
http.HandleFunc("/ws", serveWs)
Handling action:
func serveWs(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "Method not allowed", 405)
return
}
if r.Header.Get("Origin") != "http://"+r.Host {
http.Error(w, "Origin not allowed", 403)
return
}
ws, err := websocket.Upgrade(w, r, nil, 1024, 1024)
if _, ok := err.(websocket.HandshakeError); ok {
http.Error(w, "Not a websocket handshake", 400)
return
} else if err != nil {
log.Println(err)
return
}
c := &connection{send: make(chan []byte, 256), ws: ws}
h.register <- c
c.writePump()
h.unregister <- c
}
It is very similar to ordinary http request processing, also using the GET method, and the principle of Node is the same.
Another port can accept multiple tcp requests.
大家讲道理2017-04-17 11:08:14
Because WebSocket is a feature based on HTTP 1.1, it itself relies on HTTP (using the 101 status code to switch protocols). Express should know that it is already listening on that port, so it does not try to listen again (bind(2)), but only registers the processing method for HTTP WebSocket requests for requests coming from that port.
PHP中文网2017-04-17 11:08:14
It stands to reason that "or" cannot be used between TCP and HTTP.
In the OSI model, TCP is the protocol of the fourth transport layer, and HTTP is the protocol of the seventh application layer.
Your question can be understood this way. Both socket.io and Express are using the port that the node is listening to to process requests respectively, instead of listening to the port separately.