

We don’t have to install additional software or packages to use WebSockets with modern web browsers. This code uses the utf-8 charset by default. Messages can either be text or JSON encoded (JSON.stringify). Res.sendFile('/websocket-client.html', `)Īnd you can run it from the command line as follows: node index.js The web server portion will serve a single web page to the client, websocket-client.html, on port 3000: const express = require('express') The web server allows us to load our client (running in a browser), and the WebSocket server handles the bidirectional chat messages.Ĭreate the Node.js app and install both the Express.js and ‘ ws’ packages which will provide our web server and WebSocket server, respectively. This application will require both a web server (HTTP server) and a WebSocket server (wss). To build a basic chat application with WebSockets, you will need both a client and server component.įor the server, we will use Node.js, and the client-side code will run within a web browser such as Chrome. Node.js WebSocket API Example - a basic chat applicationĪll source code associated with this blog is hosted on GitHub As will be discussed later, similar functionality can be implemented using HTTP Long Polling or a hosted pub/sub service, but let’s build a simple example first using WebSockets and Node.js. WebSockets create a TCP socket connection between multiple devices or processes. The WebSocket protocol is used wherever a solution requires real-time communication and example use cases include: What types of applications use WebSockets? In other words, it allows internet-capable devices to communicate with each other, one acting as the client and the other acting as the server, with both able to initiate communication. What is a WebSocket?Ī WebSocket is a computer communications protocol providing duplex communication channels over a single TCP connection. Node JavaScript (Node.js) can be used to quickly develop and deploy this application using WebSockets, which were designed with this use case in mind. If you are reading this, you are probably interested in creating an application or service that needs two-way communication that either side can initiate.
