nodejs 网络套接字 + 没有 socket.io 的 websocket [英] nodejs net sockets + websocket without socket.io

查看:22
本文介绍了nodejs 网络套接字 + 没有 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:"和已连接"以及我是 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':仍处于连接状态.(...)"

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

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

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?

推荐答案

如果您想创建自己的 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.

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

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