Node.js网络套接字+不带socket.io的websocket [英] nodejs net sockets + websocket without socket.io

查看:114
本文介绍了Node.js网络套接字+不带socket.io的websocket的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用nodejs创建类似聊天的内容. 我是nodejs的新手,我想在没有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);

一切正常,(我认为). 当我打开localhost:7000时,我会收到有关"CONNECTED TO:"和"connected"以及"I am Chack Norris"的节点CMD消息. 之后,我尝试在浏览器控制台中编写:

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');

我遇到错误:未捕获的DOMException:无法在'WebSocket'上执行'send':仍处于CONNECTING状态.(…)"

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

一段时间后,我又收到一个错误:与'ws://localhost:7001/'的WebSocket连接失败:WebSocket打开握手超时"

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

也许此代码是错误的,但是我已经尝试了所有通过google找到的内容.有人可以帮我吗?

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

推荐答案

如果要创建自己的可以从浏览器接收webSocket连接的webSocket服务器,则必须在服务器上实现webSocket协议.这不仅仅是简单的套接字连接.它具有一个启动序列,该序列从HTTP连接开始,然后升级"到webSocket协议,包括交换安全信息,然后为通过webSocket发送的所有数据提供webSocket成帧格式.您不只是通过webSocket发送纯文本.

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.

您可以在此处查看webSocket协议的外观:编写Websocket服务器.除非您真的真的想为学习目的而创建自己的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.

然后将socket.io库构建在webSocket协议之上,并在其之上添加其他功能和消息格式.

The socket.io library is then built on top of the webSocket protocol, adding additional features and message format on top of that.

为了让您了解webSocket的连接方式,以下是典型的连接顺序:

To give you an idea how a webSocket connects, here's a typical connection sequence:

浏览器发送连接请求:

GET /chat HTTP/1.1
Host: example.com:8000
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

服务器响应:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

然后,双方都切换到webSocket协议,该协议的数据帧格式如下:

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 ...                |
+---------------------------------------------------------------+

然后,此外,还有ping和pong数据包用于保持活动测试,并且存在一种针对大数据包和碎片的方案,客户端/服务器可以协商子协议.

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.

这篇关于Node.js网络套接字+不带socket.io的websocket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆