Node.js单击按钮并使用TCP / IP协议发送内容

时间:2017-04-27 09:51:15

标签: javascript node.js tcp

我是节点新手。我正在尝试将应用程序设置为用户可以单击按钮,并且某些内容将通过TCP发送到客户端 这是我的ECHO服务器(来自nodejs.org的例子)

Clang

你能解释一下如何在另一个js文件中获取此连接。我正在尝试make const net = require('net'); var HOST = '0.0.0.0' var PORT = 6969; var server = net.createServer(); server.listen(PORT, HOST); console.log('Server listening on ' + server.remoteAddress + ':' + server.remotePort); server.on('connection', function(socket) { console.log('CONNECTED: ' + socket.remoteAddress + ':' + socket.remotePort); socket.write('Hello from server'); // other stuff is the same from here socket.on('data', function(data) { socket.write('reply data ' + data); }); }); ,但我无法理解如何从另一个文件发送信息。请帮帮我

1 个答案:

答案 0 :(得分:4)

您可以尝试这样的事情:

app.js

 var HOST = '0.0.0.0'
 var PORT = 6969;

 var server = net.createServer();
 server.listen(PORT, HOST);
 console.log('Server listening on ' + server.remoteAddress + ':' + 
 server.remotePort);

 const socket = require("./controllers/socket")(server);
 app.get("/socket/connection", socket.connection);

socket.js

const net = require('net');

module.exports = function(server) {

   module.connection = function(request, response) {

     server.on('connection', function(socket) {
       console.log('CONNECTED: ' + socket.remoteAddress + ':' + 
       socket.remotePort);
       socket.write('Hello from server');
       // other stuff is the same from here
       socket.on('data', function(data) {
          socket.write('reply data ' + data);
       });
     });


   return module;
};