Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

javascript - nodejs net sockets + websocket without socket.io

I'm trying to create something like chat using nodejs. I'm a newbie in nodejs and i want to create it without socket.io (i want to learn how it works). Here is the code i'm using.

var http = require('http');
var net = require('net');


var server = http.createServer(function(req,res){

    res.writeHead(200,{'content-type' : 'text/html'});
    res.write('<a href="./lol/">lol</a><br>');
    res.end('hello world: '+req.url);



    var client = new net.Socket();
    client.connect('7001', '127.0.0.1', function() {

        console.log('CONNECTED TO: ');
        // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client 
        client.write('I am Chuck Norris!');

    });

    // Add a 'data' event handler for the client socket
    // data is what the server sent to this socket
    client.on('data', function(data) {

        console.log('DATA: ' + data);
        // Close the client socket completely
        client.destroy();

    });

    // Add a 'close' event handler for the client socket
    client.on('close', function() {
        console.log('Connection closed');
    });
    //req.

});
server.listen(7000);


require('net').createServer(function (socket) {
    console.log("connected");

    socket.on('data', function (data) {
        console.log(data.toString());
    });
}).listen(7001);

And all works fine, (i think). When i open localhost:7000 i'm getting in node CMD messages about "CONNECTED TO:" and "connected" and "I am Chack Norris". After that i'm trying to write in the browser console:

var conn = new WebSocket('ws://localhost:7001/');

Also no errors, but when i try this line:

conn.send('lol');

I'm getting an error: "Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.(…)"

And after some time i get one more error: "WebSocket connection to 'ws://localhost:7001/' failed: WebSocket opening handshake timed out"

maybe this code is wrong, but i have tried everything that i found through google. Can someone help me with this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...