5

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 服务器将消息发送到套接字服务器两次。我是否做错了什么可能是回调或其他什么?任何帮助,将不胜感激。

4

2 回答 2

9

如果您通过浏览器调用此代码,它会向服务器发送 2 个请求。一个用于 FavIcon,一个用于页面本身。

回调中的代码被调用了两次,因为有 2 个请求。

正如马特所提到的:不要将套接字响应处理程序放在回调中,因为您失去了对它们的引用,并且为每个请求附加了一个新的处理程序。

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/');
于 2013-03-06T08:09:34.587 回答
0

client.on()调用不应该在回调内部res.end()——这会导致事件处理程序被多次附加,这意味着每次接收到数据时,都会被多次调用。

试试这个:

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");
      });   
  });
}).listen(1337, '127.0.0.1');

// 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');
});
于 2013-03-06T07:59:30.317 回答