If you want to create your own webSocket server that can receive webSocket connections from a browser, you will have to implement the webSocket protocol on your server. This is not just a socket connection. It has a startup sequence that starts as an HTTP connection, which is then “updated” to the webSocket protocol, including the exchange of security information, and then there is the webSocket framing format for all data sent via webSocket. You do not just send plain text through webSocket.
You can see what the webSocket protocol looks like here: Writing server web sites . If you really do not want to create your own webSocket server for educational purposes only, I would really suggest you get an existing module that did all the work with the nitty gritty protocol.
Then, the socket.io library is built on top of the webSocket protocol, adding additional features and a message format to it.
To give you an idea of connecting webSocket, follow a typical connection sequence:
The browser sends a connection request:
GET /chat HTTP/1.1 Host: example.com:8000 Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Sec-WebSocket-Version: 13
The server responds:
HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Then both sides switch to the webSocket protocol, which has the format of a frame data format:
0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-------+-+-------------+-------------------------------+ |F|R|R|R| opcode|M| Payload len | Extended payload length | |I|S|S|S| (4) |A| (7) | (16/64) | |N|V|V|V| |S| | (if payload len==126/127) | | |1|2|3| |K| | | +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + | Extended payload length continued, if payload len == 127 | + - - - - - - - - - - - - - - - +-------------------------------+ | |Masking-key, if MASK set to 1 | +-------------------------------+-------------------------------+ | Masking-key (continued) | Payload Data | +-------------------------------- - - - - - - - - - - - - - - - + : Payload Data continued ... : + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + | Payload Data continued ... | +---------------------------------------------------------------+
Then, in addition, there are ping and pong packages for keep-alive tests, and there is a scheme for large packages and fragmentation, and the client / server can negotiate a sub-protocol.
jfriend00
source share