Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serve WebSocket and HTTP server at same address on Node.js [closed]

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?

like image 784
Benedict Lewis Avatar asked Jan 04 '14 10:01

Benedict Lewis


People also ask

Can WebSocket and HTTP on same port?

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.

Can I use WebSockets and HTTP?

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.

Can WebSockets close servers?

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.

When WebSocket connection is closed?

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.


1 Answers

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).

like image 87
robertklep Avatar answered Oct 09 '22 22:10

robertklep