5

stackoverflow で新しく、Node で新しくなりました。

1 つの単純なソケット サーバーと 1 つの 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 回送信します。おそらくコールバックか何かで何か間違ったことをしましたか?どんな助けでも大歓迎です。

4

2 に答える 2

9

このコードをブラウザで呼び出すと、サーバーに 2 つのリクエストが送信されます。1 つは FavIcon 用で、もう 1 つはページ自体用です。

2 つの要求があるため、コールバック内のコードは 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/');
于 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 に答える