Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Would I Build A NodeJS Websocket Server Without A Library

I've recently built a small JSON webservice in NodeJS, and am interested in extending it to accept requests via WebSockets.

Most of the WebSocket tutorials I have found so far are based on 3rd party modules like SocketIO.

What does it take to write a WebSocket server? Assume that cross-browser compatibility is a non issue here, and that all my clients will have access to a decent browser.

like image 386
Charlie Avatar asked May 29 '14 12:05

Charlie


People also ask

How do I create a NodeJS WebSocket server?

Client authentication import { createServer } from 'http'; import { WebSocketServer } from 'ws'; const server = createServer(); const wss = new WebSocketServer({ noServer: true }); wss. on('connection', function connection(ws, request, client) { ws. on('message', function message(data) { console.

Is WebSocket a library?

websockets is a library for building WebSocket servers and clients in Python with a focus on correctness, simplicity, robustness, and performance. Built on top of asyncio , Python's standard asynchronous I/O framework, it provides an elegant coroutine-based API.

Is NodeJS good for WebSockets?

Node. js can maintain many hundreds of WebSockets connections simultaneously. WebSockets on the server can become complicated as the connection upgrade from HTTP to WebSockets requires handling. This is why developers commonly use a library to manage this for them.

How do I deploy a WebSocket server?

After creating your WebSocket API, you must deploy it to make it available for your users to invoke. To deploy an API, you create an API deployment and associate it with a stage. Each stage is a snapshot of the API and is made available for client apps to call.


1 Answers

Well, you'll basically just need to read the RFC and then implement it :)

At a high level WebSockets are not much more than an extended HTTP connection. They get initiated with an UPGRADE request alongside some handshaking. Afterwards the browser and server send framed messages over the existing HTTP TCP connection.

There are a few complications along the road though, as there are several versions of the WebSocket protocol out there and some of them don't support binary transport.

The RFC can be found here: https://www.rfc-editor.org/rfc/rfc6455

It's based on version 17 of the protocol. Which is, except, for some minor differences mostly Version 13.

There are still also some older Browsers around which only support the Version 6 of the protocol (where both framing and the initial handshake are quite different).

For a barebone implementation of version 6 and 13, you can check out a library of mine which pretty much does little more than to wrap the WebSocket protocol into the standard Node.js abstractions:
https://github.com/BonsaiDen/lithium/tree/master/lib

like image 173
Ivo Wetzel Avatar answered Oct 15 '22 23:10

Ivo Wetzel