NodeJS - potatoscript/websocket GitHub Wiki
Node.js is a powerful JavaScript runtime built on Chrome's V8 JavaScript engine. It is designed for building fast and scalable network applications, especially real-time applications like WebSocket-based communication systems.
WebSocket is a protocol that allows for two-way communication between a client (such as a web browser) and a server over a single, long-lived connection. WebSocket is ideal for real-time applications such as chat apps, online games, and live notifications.
In this tutorial, we will create a WebSocket server using Node.js and the ws package, which is a simple and efficient WebSocket library for Node.js.
Before we begin, you need to have Node.js installed. If you don't have it yet, download and install it from the official Node.js website.
The ws
library is a simple WebSocket library for Node.js. To install it, open your terminal or command prompt and run the following command in your project folder:
npm init -y # Initialize a new Node.js project
npm install ws # Install the ws WebSocket library
Now, let's create a WebSocket server using the ws library.
Create a file called server.js
and add the following code:
// Import the 'ws' module
const WebSocket = require('ws');
// Create a WebSocket server that listens on port 8080
const wss = new WebSocket.Server({ port: 8080 });
// When a client connects to the WebSocket server
wss.on('connection', (ws) => {
console.log('A new client connected!');
// Send a welcome message to the newly connected client
ws.send('Welcome to the WebSocket server!');
// When the server receives a message from the client
ws.on('message', (message) => {
console.log(`Received: ${message}`);
// Send a response back to the client
ws.send(`Server says: ${message}`);
});
// When the client disconnects
ws.on('close', () => {
console.log('A client disconnected');
});
});
-
WebSocket server setup: We first import the
ws
module and then create a WebSocket server that listens on port8080
. This means our server will accept WebSocket connections onws://localhost:8080
. -
Handling connections: When a client connects to the server, the
'connection'
event is triggered. We send a welcome message to the client. -
Message handling: The server listens for incoming messages with the
'message'
event. When a message is received, it sends a response back to the client. -
Client disconnection: The server listens for when the client disconnects with the
'close'
event.
Now, let's run the WebSocket server.
Open the terminal and navigate to the directory where your server.js
file is located, then run the following command:
node server.js
You should see the message WebSocket server running on ws://localhost:8080
indicating that the server is now running.
To test the WebSocket server, we need a WebSocket client. You can use a browser-based client or another Node.js application as a client.
For simplicity, weโll use an HTML file with JavaScript to create a client that connects to the WebSocket server.
Create an index.html
file and add the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket Client</title>
</head>
<body>
<h2>WebSocket Client</h2>
<!-- Message display area -->
<div id="messages" style="height: 200px; width: 300px; overflow-y: scroll; border: 1px solid black; margin-bottom: 10px;">
</div>
<!-- Input for sending messages -->
<input type="text" id="messageInput" placeholder="Type a message" />
<button onclick="sendMessage()">Send Message</button>
<script>
// Create a new WebSocket connection to the server
const socket = new WebSocket('ws://localhost:8080');
// When the WebSocket connection is opened
socket.onopen = () => {
console.log('Connected to WebSocket server');
};
// When the WebSocket receives a message from the server
socket.onmessage = (event) => {
const messagesDiv = document.getElementById('messages');
const newMessage = document.createElement('div');
newMessage.textContent = event.data;
messagesDiv.appendChild(newMessage); // Add the new message to the display area
};
// Function to send a message to the WebSocket server
function sendMessage() {
const message = document.getElementById('messageInput').value;
if (message) {
socket.send(message); // Send the message to the server
document.getElementById('messageInput').value = ''; // Clear the input field
}
}
</script>
</body>
</html>
- The
WebSocket('ws://localhost:8080')
establishes a connection to the WebSocket server that is running onlocalhost
at port8080
. - The
onopen
event triggers when the connection is successfully established. - The
onmessage
event handles incoming messages from the server and displays them in themessages
div. - The
sendMessage
function sends the message typed in the input field to the WebSocket server.
-
Run the WebSocket Server: If it's not already running, start the server using the
node server.js
command. -
Open the HTML Client: Open the
index.html
file in your web browser. -
Send Messages: Type a message in the input field and click the "Send Message" button. The message will be sent to the server, and the server will respond with
Server says: <your message>
, which will be displayed in themessages
div.
To handle when clients disconnect from the WebSocket server, you can use the 'close'
event. Hereโs an example of how to notify the server when a client disconnects:
wss.on('connection', (ws) => {
console.log('A new client connected!');
ws.on('close', () => {
console.log('A client disconnected');
});
});
The 'close'
event fires when the client disconnects, either manually or due to network issues.
To broadcast messages to all connected clients, you can iterate over all WebSocket connections and send the message to each one. Hereโs an example of how to do it:
wss.on('connection', (ws) => {
console.log('A new client connected!');
ws.on('message', (message) => {
console.log(`Received: ${message}`);
// Broadcast the message to all connected clients
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
});
-
wss.clients
contains all connected clients. - We loop through each client and send the message to all other clients except the one that sent the message.
In this tutorial, weโve covered the following:
- How to set up a WebSocket server in Node.js using the ws library.
- How to create a WebSocket client in HTML and JavaScript.
- How to handle messages between the client and server.
- How to handle client disconnects and broadcast messages to all connected clients.