If you want to create your own webSocket server that can receive webSocket connections from the browser, you will have to implement the webSocket protocol on your server. It is not just a simple socket connection. It has a startup sequence that starts as an HTTP connection that is then "upgraded" to the webSocket protocol, including an exchange of security info and then there is a webSocket framing format for all data sent over the webSocket. You don't just send plain text over a webSocket.
You can see what the webSocket protocol looks like here: Writing Websocket Servers. Unless you really want to make your own webSocket server just for learning purposes, I'd really suggest you get an existing module that has done all the nitty gritty protocol work for you.
The socket.io library is then built on top of the webSocket protocol, adding additional features and message format on top of that.
To give you an idea how a webSocket connects, here's a typical connection sequence:
Browser sends connect request:
GET /chat HTTP/1.1
Host: example.com:8000
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
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 a data framing format like this:
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 packets for keep-alive tests and there is a scheme for large packets and fragmentation and client/server can negotiate a sub-protocol.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…