Reputation: 75
What exactly does code something like
var WebSocketServer = require("ws").Server,
express = require("express"),
http = require("http"),
app = express(),
server = http.createServer(app);
var wss = new WebSocketServer({server: server});
mean? What is that really doing - why would you need to give a websocket server an http server?
Upvotes: 2
Views: 1512
Reputation: 707158
All webSocket connections start with an http request from the client (that contains an upgrade
header). Once both sides agree that an upgrade to the webSocket protocol is OK and have exchanged some security credentials, then the protocol is upgraded to the webSocket protocol and all future communication on that socket is using the webSocket protocol, not the http protocol.
But, EVERY webSocket server has to be an http server for the webSocket initiation process.
You can choose whether you want this http server to be a shared http server that is also being used for your own http requests or whether you want a separate http server to be created just for the webSocket connections. If you use the separate http server, then it will have to be on a separate port (since you can't have two servers on the same host operating on the same port).
When using the shared http server, there is a small webSocket listener that examines each incoming http request. If that incoming request contains the Upgrade: websocket
header, then it takes over that incoming request. If not, it lets the regular http server logic handle the request as a normal http request. In this manner, the same http server can be used for both http requests and incoming websocket connection requests.
So, by sharing with the http server, everything (both your http requests and your webSocket connections) can operate on the usual default ports, port 80 (for http) or port 443 (for https).
Some relevant references:
Why WebSocket can share the 80 port with HTTP "after the handshake"?
Do websocket implementations use http protocol internally?
What's the difference between WebSocket and plain socket communication?
Examples of establishing a websocket protocol connection over http
Upvotes: 5
Reputation: 31805
That's because a WebSocket connection is often an Upgrade
from a HTTP one. The HTTP server handles the full handshake with the client, then delegates everything else to WebSocket. See Protocol upgrade mechanism for more informations on this.
Upvotes: 0