node js net sockets + websocket without socket.io [英] node js net sockets + websocket without socket.io

查看:281
本文介绍了node js net sockets + websocket without socket.io的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用node.js创建类似char的东西
我是nodejs中的新手,我想在没有socket.io的情况下创建它(我想了解它是如何工作的)。
这是我正在使用的代码。

I trying to create something like char using node.js I am 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时,我收到节点CMD消息CONNECTED TO:和connected以及我是Chack Norris。
之后我尝试在浏览器控制台中编写:

And all works fine, (i think). When i'm 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 write in browser console:

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

也没有错误,但是当我尝试这一行时:

Also no errors, but when i'm trying this line:

conn.send('lol');

我收到错误:未捕获DOMException:无法在'WebSocket'上执行'send':仍然处于CONNECTING状态。(...)

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

过了一段时间我又得到了一个错误:WebSocket连接到'ws:// localhost:7001 /'失败:WebSocket打开握手超时

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

也许这段代码是错误的,但我已经尝试了我发现扔掉谷歌的一切。有人可以帮我吗?

maybe this code is wrong, but i have tryed everything that i found throw the 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.

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

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协议whi ch有这样的数据框架格式:

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 net sockets + websocket without socket.io的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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