WebSocket servers start out as HTTP servers, then the browser connects to the HTTP server and asks to upgrade; at this point, the WebSocket protocol logic takes over.
We supply an HTTP server instance to the WebSocket server at initialization time by passing it in the options object (we use ES6 shorthand to set a property of server with the value being the server instance).
When we navigate the browser to http://localhost:8080, an HTTP request is made and we send our in-memory public/index.html file as the response.
As soon as the HTML is loaded in the browser, the inline script is executed and the WebSocket upgrade request is made to our server.
When the server receives this WebSocket upgrade request, our WebSocket server instance (wss) emits a connection event that supplies socket as the first parameter of the connection event handler function.
The socket parameter is an instance of EventEmitter; we use its message event to respond to incoming messages on the established WebSocket connection.
In the message event handler function, we log the received data and the client IP address to the terminal and check whether the incoming message is Hello. If it is, we use the socket.send method to respond to the client with WebSockets!.