简体   繁体   English

nodejs 网络套接字 + 没有 socket.io 的 websocket

[英]nodejs net sockets + websocket without socket.io

I'm trying to create something like chat using nodejs.我正在尝试使用 nodejs 创建类似聊天的东西。 I'm a newbie in nodejs and i want to create it without socket.io (i want to learn how it works).我是 nodejs 的新手,我想在没有 socket.io 的情况下创建它(我想了解它是如何工作的)。 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".当我打开 localhost:7000 时,我会收到有关“CONNECTED TO:”和“已连接”以及“我是 Chack Norris”的节点 CMD 消息。 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.(…)"我收到一个错误:“未捕获的 DOMException:无法在‘WebSocket’上执行‘发送’:仍处于连接状态。(...)”

And after some time i get one more error: "WebSocket connection to 'ws://localhost:7001/' failed: WebSocket opening handshake timed out"一段时间后,我又收到一个错误:“与 'ws://localhost:7001/' 的 WebSocket 连接失败:WebSocket 打开握手超时”

maybe this code is wrong, but i have tried everything that i found through google.也许这段代码是错误的,但我已经尝试了通过谷歌找到的所有内容。 Can someone help me with this?有人可以帮我弄这个吗?

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.如果你想创建自己的 webSocket 服务器,可以从浏览器接收 webSocket 连接,你必须在你的服务器上实现 webSocket 协议。 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.它有一个启动序列,从一个 HTTP 连接开始,然后“升级”到 webSocket 协议,包括安全信息的交换,然后有一个 webSocket 帧格式,用于通过 webSocket 发送的所有数据。 You don't just send plain text over a webSocket.您不只是通过 webSocket 发送纯文本。

You can see what the webSocket protocol looks like here: Writing Websocket Servers .您可以在此处查看 webSocket 协议的样子: 编写 Websocket 服务器 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.除非你真的想制作你自己的 webSocket 服务器只是为了学习目的,否则我真的建议你获得一个现有的模块,它已经为你完成了所有的细节协议工作。

The socket.io library is then built on top of the webSocket protocol, adding additional features and message format on top of that.然后 socket.io 库建立在 webSocket 协议之上,在此之上添加额外的功能和消息格式。

To give you an idea how a webSocket connects, here's a typical connection sequence:为了让您了解 webSocket 是如何连接的,下面是一个典型的连接序列:

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:然后,双方切换到具有如下数据帧格式的 webSocket 协议:

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.然后,此外,还有用于保活测试的 ping 和 pong 数据包,还有用于大数据包和分片的方案,客户端/服务器可以协商子协议。

As suggested above, better not write your own socket server unless you really need/want to.如上所述,除非您确实需要/想要,否则最好不要编写自己的套接字服务器。

A great socket server with a simple interface is ws https://github.com/websockets/ws具有简单界面的出色套接字服务器是ws https://github.com/websockets/ws

With just a few lines you can start sending and receiving messages server-side.只需几行,您就可以开始在服务器端发送和接收消息。

Meanwhile, on the client-side you don't need a library, just:同时,在客户端,您不需要库,只需:

new WebSocket('wss//echo.websocket.org')

read more阅读更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM