参见英文答案 nodejs – http.createServer seems to call twice2个 stackoverflow新增,Node新增. 我有一个简单的套接字服务器和一个Web服务器. 如果有人连接了Web服务器,我希望Web服务器向套接字服务器
stackoverflow新增,Node新增.
我有一个简单的套接字服务器和一个Web服务器.
如果有人连接了Web服务器,我希望Web服务器向套接字服务器发送消息.
浏览器< => Web服务器/套接字客户端< =>套接字服务器
我创建了这样的服务器:
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服务器将消息发送到套接字服务器两次.
我是否做错了可能回调或其他什么?
任何帮助,将不胜感激.
回调中的代码被调用两次,因为有2个请求.
正如Matt所说:不要将套接字响应处理程序放在回调中,因为你松开了对它们的引用,并为每个请求附加了一个新的处理程序.
var http = require('http'); var net = require('net'); var HOST = '192.168.1.254'; var PORT = 8888; var client = new net.Socket(); var url = require('url'); http.createServer(function (req, res) { console.log(url.parse(req.url)); res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n', function(){ console.log('Connected To: ' + HOST + ':' + PORT); }); }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/');