简体   繁体   English

TCP将消息发送到端口上的localhost-node.js

[英]TCP send message to localhost on port - node.js

I am trying to create using nodes core only a message sent by one server to another server (not clients just server-to-server). 我正在尝试使用节点创建由一台服务器发送到另一台服务器(而不是客户端到服务器)的消息的核心

In fact the servers are both the same server message is sent between 2 apps that must not be linked together. 实际上,这两个服务器是同一服务器消息,它们是在两个不能链接在一起的应用程序之间发送的。 one must receive a remote message from the other. 一个必须从另一个接收远程消息。

I am looking over all google things and node docs but can't make sense of a few parts of the code for sending. 我正在查看所有Google事物和节点文档,但无法理解发送代码的几部分。

The first server only should receive messages: 第一台服务器应仅接收以下消息:

var net=require('net');

var server1=net.createServer(function(nets){
    nets.addListener('message',function(data){
        console.dir(data);
        });
    });
server1.listen(8000,'localhost');

The second server should only send messages: 第二台服务器应仅发送消息:

var net=require('net');

var server2=net.createConnection(8000,'localhost',function(nets){
    nets.on('connect',function(){
        nets.write('message',{'a':1,'foo':'bar'});
        });
});

I am having trouble understanding the docs though, I defiantly need to use net because the 2 apps must not be attached to each other so eventEmitter is a no-no 我在理解文档时遇到了麻烦,但我绝对需要使用net,因为2个应用程序不能相互连接,所以eventEmitter是一个禁忌

The node.js documentation has some easy examples of both a TCP server as well as a TCP client that you can tweak for your application-specific logic. node.js文档提供了一些简单的TCP服务器实例和TCP客户端实例,您可以根据自己的应用程序逻辑进行调整。

Also: the documentation for Socket shows what you can do with an incoming or outgoing socket connection. 另外: 套接字的文档显示了可以使用传入或传出套接字连接执行的操作。 As you will see, you cannot write JSON directly with node core. 正如您将看到的,您不能直接用节点核心编写JSON。 You have to stringify it first: sock.write(JSON.stringify({ foo: 'bar' })); 您必须先对其进行字符串化: sock.write(JSON.stringify({ foo: 'bar' }));

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

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