Welcome to the Websockets tutorial! Websockets provide a full-duplex communication channel over a single, long-lived connection. This is different from traditional HTTP requests, which are stateless and require a new connection for each request.

Basic Concepts

  • WebSocket Protocol: A protocol enabling two-way communication between the client and server.
  • Client and Server: The client is typically the browser, and the server is the web server that hosts the WebSocket connection.
  • Handshake: The initial HTTP request that upgrades the connection to a WebSocket connection.

Getting Started

To get started with Websockets, you can use the following steps:

  1. Create a WebSocket Server: Set up a server that can handle WebSocket connections.
  2. Create a WebSocket Client: Write a client that can connect to the WebSocket server.
  3. Send and Receive Messages: Implement the logic to send and receive messages between the client and server.

Example

Here's a simple example of a WebSocket server and client:

// WebSocket Server
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });

  ws.send('something from server');
});

// WebSocket Client
const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost:8080');

ws.on('open', function open() {
  ws.send('Hello Server!');
});

ws.on('message', function incoming(data) {
  console.log(data);
});

More Resources

For more information on Websockets, check out the following resources:

WebSocket Diagram