WebSocket
Network Requests: WebSocket
Can you briefly describe the WebSocket protocol?
View Answer:
What protocol does WebSocket use?
View Answer:
What do we need to open a WebSocket connection?
View Answer:
Syntax: let socket = new WebSocket("ws://hellojavascript.info");
Here's a simple example of how you can establish a WebSocket connection using JavaScript:
// Creating a new WebSocket
let socket = new WebSocket('ws://hellojavascript.info');
// Connection opened
socket.addEventListener('open', (event) => {
socket.send('Hello Server!');
});
// Listen for messages
socket.addEventListener('message', (event) => {
console.log('Message from server: ', event.data);
});
// Connection closed
socket.addEventListener('close', (event) => {
console.log('Server connection closed', event);
});
// Error handler
socket.addEventListener('error', (event) => {
console.log('WebSocket error: ', event);
});
This example will open a new WebSocket connection to the server at 'ws://your-websocket-server.com'. It will send a message 'Hello Server!' once the connection is open and log any messages received from the server.
Remember to replace 'ws://your-websocket-server.com'
with the actual WebSocket server URL you intend to connect to. If your server supports secure WebSocket connections (WSS), then your URL should start with 'wss://'
.
Please ensure that your server is configured correctly to accept WebSocket connections, otherwise you won't be able to establish the connection from your client-side code.
What is the preferred mode for a WebSocket connection?
View Answer:
let socket = new WebSocket(
'wss://hellojavascript.info/blog/websocket/demo/hello'
);
What events may we listen for after establishing a WebSocket connection?
View Answer:
let socket = new WebSocket(
'wss://javascript.info/article/websocket/demo/hello'
);
socket.onopen = function (e) {
console.log('[open] Connection established');
console.log('Sending to server');
socket.send('My name is John');
};
socket.onmessage = function (event) {
console.log(`[message] Data received from server: ${event.data}`);
};
socket.onclose = function (event) {
if (event.wasClean) {
console.log(
`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`
);
} else {
// e.g. server process killed or network down
// event.code is usually 1006 in this case
console.log('[close] Connection died');
}
};
socket.onerror = function (error) {
console.log(`[error] ${error.message}`);
};
What happens during the initial state of opening a WebSocket connection?
View Answer:
GET /chat
Host: javascript.info
Origin: https://javascript.info
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Key: Iv8io/9s+lYFgZWcXczP8Q==
Sec-WebSocket-Version: 13
What does the origin refer to in WebSocket connections in the browser header?
View Answer:
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', (ws, req) => {
const origin = req.headers.origin;
console.log(`Connection requested from origin: ${origin}`);
// Here you can decide whether to accept or reject the connection based on the origin
// For this example, let's only accept connections from 'http://your-website.com'
if (origin !== 'http://your-website.com') {
ws.close();
console.log(`Connection rejected for origin: ${origin}`);
} else {
console.log(`Connection accepted for origin: ${origin}`);
}
ws.on('message', (message) => {
console.log(`Received message: ${message}`);
});
});
Please note that CORS (Cross-Origin Resource Sharing) and the Origin header work differently in WebSocket protocol compared to HTTP. In HTTP, the browser prevents the site from seeing the response from cross-origin requests unless the server opts in. However, in WebSocket once the connection is established, the data can flow in any direction regardless of the origin. Therefore, it's up to the server to validate the Origin header and decide whether to accept the connection or not.
What does the connection upgrade signal?
View Answer:
What happens after the connection upgrade request with a WebSocket?
View Answer:
Can the WebSocket handshake be emulated with XMLHttpRequest or fetch?
View Answer:
What server code response does the server send during a switch WebSocket protocol?
View Answer:
101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: hsBlbuDTkk24srzEOTBUlZAlC2g=
What does deflate-frame imply in terms of Sec-WebSocket-Extensions?
View Answer:
What does the Sec-WebSocket-Protocol: soap, wamp specify?
View Answer:
<script>
let socket = new WebSocket('wss://javascript.info/chat', ['soap', 'wamp']);
</script>
GET/chat
Host: javascript.info
Upgrade: websocket
Connection: Upgrade
Origin: https://javascript.info
Sec-WebSocket-Key: Iv8io/9s+lYFgZWcXczP8Q==
Sec-WebSocket-Version: 13
Sec-WebSocket-Extensions: deflate-frame
Sec-WebSocket-Protocol: soap, wamp
101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: hsBlbuDTkk24srzEOTBUlZAlC2g=
Sec-WebSocket-Extensions: deflate-frame
Sec-WebSocket-Protocol: soap
What exactly are frames in the context of WebSocket communication?
View Answer:
Can you explain the function of the WebSocket.send() method?
View Answer:
When WebSocket returns text or binary data to us, what object type is it?
View Answer:
socket.binaryType = 'arraybuffer';
socket.onmessage = (event) => {
// event.data is either a string (if text) or arraybuffer (if binary)
};
How should we deal with a sluggish network connection in the context of WebSocket communication?
View Answer:
Enabling compression with WebSocket connection requires support from both the server and the client. The client can request compression in the connection handshake, but the server must agree to use it.
You should use the 'ws' library in Node.js for the server and JavaScript's built-in WebSocket API for the client. The 'ws' library supports permessage-deflate compression.
Client-side (JavaScript):
let socket = new WebSocket('ws://your-websocket-server.com', [], {
perMessageDeflate: true
});
socket.addEventListener('open', (event) => {
socket.send('Hello, server!');
});
socket.addEventListener('message', (event) => {
console.log('Message from server: ', event.data);
});
In the client-side code, perMessageDeflate: true
is used to indicate that the client is willing to use permessage-deflate compression.
Server-side (Node.js):
const WebSocket = require('ws');
const wss = new WebSocket.Server({
port: 8080,
perMessageDeflate: {
zlibDeflateOptions: {
// See zlib defaults.
chunkSize: 1024,
memLevel: 7,
level: 3
},
zlibInflateOptions: {
chunkSize: 10 * 1024
},
// Other options settable:
clientNoContextTakeover: true, // Defaults to negotiated value.
serverNoContextTakeover: true, // Defaults to negotiated value.
serverMaxWindowBits: 10, // Defaults to negotiated value.
// Below options specified as default values.
concurrencyLimit: 10, // Limits zlib concurrency for perf.
threshold: 1024 // Size (in bytes) below this use BYTEFRAMING
}
});
wss.on('connection', (ws) => {
ws.on('message', (message) => {
console.log(`Received: ${message}`);
ws.send('Hello, client!');
});
});
In the server-side code, the 'ws' library allows fine control over the deflate options. We enable the permessage-deflate extension and provide some configuration options.
Remember to replace 'ws://your-websocket-server.com'
with the actual WebSocket server URL you intend to connect to.
While compression can help reduce the size of the messages transmitted, it does increase the CPU load because of the computational cost of the compression/decompression operations. Depending on the use case, it might be more beneficial to use compression for larger payloads and forego it for smaller ones.
What happens when either the browser or server closes a connection?
View Answer:
Syntax: socket.close([code], [reason]);
// closing party:
socket.close(1000, 'Work complete');
// the other party
socket.onclose = (event) => {
// event.code === 1000
// event.reason === "Work complete"
// event.wasClean === true (clean close)
};
What are the standard closure codes for WebSocket?
View Answer:
// in case connection is broken
socket.onclose = (event) => {
// event.code === 1006
// event.reason === ""
// event.wasClean === false (no closing frame)
};