用 NodeJS 编写的简单 TCP 服务器中的 socket.emit?

发布于 2024-11-27 19:15:28 字数 693 浏览 0 评论 0原文

[正如你将看到的,我不太了解 TCP 服务器和客户端的基本概念,可能 socket.emit 甚至不可能,但我想知道最好的替代方案或类似的东西......]

Socket.io 有一个漂亮的东西可以发出事件并在另一端捕获它们,它位于它的首页(http://socket.io)。我可以做类似的事情,但使用 NodeJS 的常规“net”模块吗?如果不是那么相当于什么?

我尝试过:

server.js

var server = net.createServer(function(socket) {
    socket.on("connect",function() {
        socket.emit('test',{msg : 'did you get it ?'});
    });
}).listen(8000);

client.js

var client = net.createConnection(8000, localhost);
client.on('connect',function(){
    client.on('test',function(data) {
        console.log(data.toString());
    });
});

但正如你可以想象的,它不起作用。我怎样才能做到这一点?

提前致谢。

[as you'll see, I don't understand the basic concepts of a TCP server and client very well and probably socket.emit is not even possible, but I'd like to know the best alternative or similar thing...]

Socket.io has a beautiful thing to emit events and catch them on the other side, it's in it's first page (http://socket.io). Can I do something similar like that but with NodeJS' regular 'net' module ? If not then what's the equivalent ?

I tried:

server.js

var server = net.createServer(function(socket) {
    socket.on("connect",function() {
        socket.emit('test',{msg : 'did you get it ?'});
    });
}).listen(8000);

client.js

var client = net.createConnection(8000, localhost);
client.on('connect',function(){
    client.on('test',function(data) {
        console.log(data.toString());
    });
});

But as you can imagine, it does not work. How can I achieve this ?

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

等风来 2024-12-04 19:15:28

嗯,net 只是 TCP 的一个接口。要发送和接收消息,您需要在 TCP 之上设计和实现您自己的协议。 TCP是面向流的协议,而不是面向消息的协议。这意味着您必须发明一种让读者分隔消息的方法。分隔消息的最简单方法是在消息之间插入 \n 字符。将消息编码为字节流的最简单方法是使用 JSON.stringify。所以:

client.js

var Lazy = require('lazy'), net = require('net')

var client = net.createConnection(8000)

new Lazy(client).lines.forEach(function (msg)
{
    console.log(JSON.parse(msg))    
})

server.js

var net = require('net')

var server = net.createServer(function(socket) {
    socket.on("connect",function() {
    var str = JSON.stringify({foo : 'test', msg : 'did you get it ?'}) + "\n"
        socket.write(str)
    });
}).listen(8000);

可以从这里开始,详细阐述。例如,您可以在接收方使用 EventEmitter 库类,并在收到不同消息时发出不同的事件。

NPM 上提供了“惰性”模块,用于将接收字节流拆分为单独的行。拆分可以手动完成,但需要 20 多行代码。请参阅“脏”NPM 模块的来源,了解拆分的示例实现 - 它很麻烦,因此在这种情况下具有外部依赖项是有根据的。

Well, net is just an interface to TCP. To send and receive messages you need to design and implement your own protocol on top of TCP. TCP is a stream-oriented protocol and not message-oriented. This means that you must invent a way for the reader to separate messages. The simplest way to separate messages are to insert \n characters between them. The simplest way to encode messages as a byte stream is to use JSON.stringify. So:

client.js

var Lazy = require('lazy'), net = require('net')

var client = net.createConnection(8000)

new Lazy(client).lines.forEach(function (msg)
{
    console.log(JSON.parse(msg))    
})

server.js

var net = require('net')

var server = net.createServer(function(socket) {
    socket.on("connect",function() {
    var str = JSON.stringify({foo : 'test', msg : 'did you get it ?'}) + "\n"
        socket.write(str)
    });
}).listen(8000);

You can start from this and elaborate. For example, you can use EventEmitter library class on receiver side and emit different events upon receiving different messages.

The 'lazy' module is available on NPM and is used to split the receiving byte stream into separate lines. The splitting is doable by hand, but it will require like 20 more lines of code. See the sources of 'dirty' NPM module for en example implementation of splitting - it's cumbersome, so having an external dependency is well-grounded in this case.

被你宠の有点坏 2024-12-04 19:15:28

Socket.io 使用 socket.io-parser 的编码/解码方法在服务器和客户端之间传输消息,这意味着它实际上在幕后使用流。

Socket.io uses socket.io-parser's encode/decode method to transfer messages between server and client, which means it actually uses stream under the hood.

沉默的熊 2024-12-04 19:15:28

只是想提一下,在 Nodejs 版本 5.0.0 中,已经有一个客户端,以防您想跳过使用 lazy

var client = net.connect({port: 8000},
    function() { //'connect' listener
       console.log('connected to server!');
});

client.on('data', function(data) {
  console.log(data.toString());
  client.end();
});

client.on('end', function() {
  console.log('disconnected from server');
});

Just wanted to mention that in Nodejs Version 5.0.0, there's already a client in case you wanna skip using lazy:

var client = net.connect({port: 8000},
    function() { //'connect' listener
       console.log('connected to server!');
});

client.on('data', function(data) {
  console.log(data.toString());
  client.end();
});

client.on('end', function() {
  console.log('disconnected from server');
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文