Step 1: server
I've created a simple server with Node & Socket.io which declares a namespace under /my-namespace. Once somebody connects, emit a confirmation msg as CONNECT_ACK and emit 3 seconds later another event (for example SOME_EVENT) with a payload:
const express = require('express');
const http = require('http');
const socketIO = require('socket.io');
let app = express();
let server = http.createServer(app);
server.listen(3000, () => {
console.log('server listening on port 3000');
let io = new socketIO(server);
io.of('/my-namespace').on('connection', (socket) => {
console.log('welcome!');
socket.emit('CONNECT_ACK');
setTimeout(() => {
io.of('/my-namespace').emit('SOME_EVENT', { a: 4 });
}, 3000);
});
});
Step 2: client
Then, I created the smallest client side which just connects to the namespace and logs when it receives CONNECT_ACK or SOME_EVENT
<!doctype html>
example
const endPoint = "http://localhost:3000/my-namespace";
io(endPoint)
.on('CONNECT_ACK', () => { console.log("I've connected"); })
.on('SOME_EVENT', (data) => { console.dir(data); });
Step 3: Checking everything is awesome
Running the client node index.js and serving the html (I use Python Simple Server) I got the desired in both consoles:
Step 4. Understanding whats going on here
Now, when I opened the Network Chrome tab I started writing this long post. These are the requests:
[WebSocket Protocol]: GET to /socket.io (not to /my-channel) receiving some confirmation bits; POST again to /socket.io including those confirmation bits. OK.
[I don't get this]: again a GET to /socket.io including the confirmation bits which now resolves to the CONNECT_ACK event: ÿ40ÿ40/my-namespaceÿ42/my-namespace,["CONNECT_ACK"]. This is the only event I'm going to receive this way.
[WS]: A GET to /socket.io indicating it's a websoket returns me a 101 (Switching Protocols) and I can recieve the msgs as: 42/my-namespace,["SOME_EVENT",{"a":4}] which is the event I send from the server & some 2s or 3s periodically
[I don't get this too]: again a GET to /socket.io including the confirmation bits which now resolves to this thing: ÿ6
Why does the client asks for socket.io instead of /my-channel?
Why there is a GET after the WS handshake which receives CONNECT_ACK msg?
I understand that the "inmortal" request which resolves in 101 is the socket itself, and those 2s and 3s are just periodical checks.
Why does all the events start by 42 (I've checked this does not change)
What is that final GET? is it part of the WS protocol?
JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)