stackoverflow 的新功能和 Node.js 的新功能。
我有一个简单的套接字服务器和一个 Web 服务器。
如果有人连接了 Web 服务器,我希望 Web 服务器向套接字服务器发送消息。
浏览器 <=> Web 服务器/Socket 客户端 <=> Socket 服务器
我创建了这样的服务器:
var http = require('http');
var net = require('net');
var HOST = '192.168.1.254';
var PORT = 8888;
var client = new net.Socket();
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n', function(){
client.connect(PORT, HOST, function() {
console.log('Connected To: ' + HOST + ':' + PORT);
client.write('0109001' + "\n");
});
// 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('The Data: ' + data);
client.destroy();
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});
});
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
此代码有效,但 Web 服务器将消息发送到套接字服务器两次。我是否做错了什么可能是回调或其他什么?任何帮助,将不胜感激。