Introduction to WebSockets - CSU677 - Shoolini U

WebSockets

1. Introduction to WebSockets

WebSockets is a communication protocol that provides full-duplex communication channels over a single TCP connection. Unlike HTTP, which is request-response based, WebSockets allow for persistent connections between the client and server, enabling real-time data exchange. This makes WebSockets ideal for applications that require low-latency communication, such as live chat, online gaming, financial tickers, and collaborative tools.

2. How WebSockets Work

WebSockets start with an HTTP handshake, after which the connection is upgraded from HTTP to WebSockets. Once established, the connection remains open, allowing messages to be sent back and forth between the client and server without the need to re-establish the connection each time.

2.1 WebSocket Handshake

The WebSocket protocol begins with a handshake that looks similar to an HTTP request. This handshake is initiated by the client, and if the server supports WebSockets, it responds with a status code of 101 Switching Protocols, indicating that the connection is being upgraded.

2.1.1 Example: WebSocket Handshake

GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

If the server accepts the WebSocket connection, it responds with:


HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

After this handshake, the connection is established, and the client and server can start exchanging data.

3. WebSocket API

The WebSocket API in the browser provides a simple interface for creating and managing WebSocket connections. It allows you to send and receive messages through the WebSocket connection.

3.1 Creating a WebSocket Connection

To create a WebSocket connection in a web application, you can use the WebSocket constructor, passing the WebSocket server URL as an argument.

3.1.1 Example: Creating a WebSocket Connection

const socket = new WebSocket('ws://example.com/socketserver');

// Event listener for when the connection is opened
socket.addEventListener('open', function (event) {
    socket.send('Hello Server!');
});

// Event listener for when a message is received from the server
socket.addEventListener('message', function (event) {
    console.log('Message from server ', event.data);
});

In this example, a WebSocket connection is created to the server at ws://example.com/socketserver. Once the connection is open, a message is sent to the server. The connection also listens for messages from the server and logs them to the console.

4. Sending and Receiving Data

Once a WebSocket connection is established, you can use the send() method to send data to the server. Similarly, you can listen for incoming messages from the server using the message event.

4.1 Sending Messages

Messages can be sent through the WebSocket connection using the send() method. The data can be in the form of a string, Blob, ArrayBuffer, or any other type supported by the WebSocket API.

4.1.1 Example: Sending Data

socket.send('Hello, server!');

// Sending binary data (e.g., an ArrayBuffer)
const arrayBuffer = new Uint8Array([1, 2, 3, 4]).buffer;
socket.send(arrayBuffer);

This example demonstrates sending both text and binary data to the server through a WebSocket connection.

4.2 Receiving Messages

To handle incoming messages, you can set up an event listener for the message event. The event.data property contains the data sent by the server.

4.2.1 Example: Receiving Data

socket.addEventListener('message', function (event) {
    console.log('Message from server ', event.data);
});

In this example, any messages received from the server are logged to the console.

5. WebSocket Events

WebSocket connections have several events associated with them that help manage the connection lifecycle:

5.1 Handling WebSocket Events

Each of these events can be handled by adding event listeners to the WebSocket object.

5.1.1 Example: Handling WebSocket Events

const socket = new WebSocket('ws://example.com/socketserver');

socket.addEventListener('open', function (event) {
    console.log('Connected to the server');
});

socket.addEventListener('message', function (event) {
    console.log('Received data: ', event.data);
});

socket.addEventListener('error', function (event) {
    console.error('WebSocket error: ', event);
});

socket.addEventListener('close', function (event) {
    console.log('WebSocket connection closed: ', event);
});

In this example, event listeners are added to handle the different stages of the WebSocket connection lifecycle. The open event logs a message when the connection is established, the message event logs any incoming data, the error event logs errors, and the close event logs when the connection is closed.

6. Closing a WebSocket Connection

Closing a WebSocket connection can be done using the close() method. This method allows you to gracefully close the connection, optionally providing a reason for the closure.

6.1 Example: Closing a WebSocket Connection


socket.close(); // Closes the connection
// Closing with a code and reason
socket.close(1000, 'Work complete');

The close() method can be called with an optional status code and reason. The status code indicates the reason for closure, with 1000 being a normal closure. The second parameter is a string that provides a human-readable explanation.

7. WebSocket Security Considerations

While WebSockets provide powerful capabilities for real-time communication, they also introduce potential security risks. It's important to be aware of these risks and implement best practices to secure your WebSocket connections.

7.1 Securing WebSocket Connections

WebSocket connections should use the wss:// protocol, which is the secure version of WebSockets, similar to HTTPS for HTTP. This ensures that the data transmitted between the client and server is encrypted.

7.1.1 Example: Secure WebSocket Connection

const secureSocket = new WebSocket('wss://example.com/socketserver');

In this example, the WebSocket connection is established using the wss:// protocol, ensuring that the communication is encrypted.

7.2 Other Security Practices

8. Use Cases for WebSockets

WebSockets are ideal for applications that require real-time communication between the client and server. Here are some common use cases: