I have set up a Websocket server on port 8888, using Node.js. I also have an interface for that which interacts with the Websocket backend (chat server).
How do I serve the index.html (with it's CSS/JS files) when the server is accessed using a browser?
Protocol handshake The handshake starts with an HTTP request/response, allowing servers to handle HTTP connections as well as WebSocket connections on the same port.
ANY WebSocket implementation MUST use HTTP (and all semantics therein, including authentication, redirection, etc) for the initial handshake. It is mandated by the WebSocket protocol specification, RFC 6455. So, a dedicated WebSockets server must be able to handle HTTP requests during the handshake phase, at least.
Either the client or the server sends a Close frame (WebSockets borrow a lot of TCP terminology, so you exchange data in “frames”), and the other side sends back its own Close frame in response, and then both parties can close their connections.
The WebSocket is closed before the connection is established error message indicates that some client code, or other mechanism, has closed the websocket connection before the connection was fully established.
If you don't want to use socket.io
, but the websocket
package, you can use it in combination with Express like this:
// app.js
var WebSocketServer = require('websocket').server;
var express = require('express');
var app = express();
var server = app.listen(8888);
var wsServer = new WebSocketServer({ httpServer : server });
// this will make Express serve your static files
app.use(express.static(__dirname + '/public'));
// the rest of your code
wsServer.on('request', function(r) { ...
express.static
will take care of serving your HTML/CSS/JS files. The argument you pass is the directory where those files are located (in this case, the directory public/
relative to where app.js
is located).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With