1

クライアントがajaxリクエストを介してローカルソケットサーバーに接続し、システムを更新するたびに、接続されているすべてのクライアントを更新できるようにする必要があるアプリケーションを作成しています。リクエストの処理は問題ありませんが、ローカルソケットサーバーからsocket.ioに応答を送信して全員にブロードキャストすることが問題です。ここで見ているのは単純なものだと確信していますが、これは私にとって非常に新しいので、特に非同期プログラミングの考え方に問題があります。以下は、私が達成しようとしていることと、私が行き詰まっている場所の短縮版です。

var express = require('express'),
    http    = require('http'),
    net     = require('net'),
    app     = express(),
    server  = http.createServer(app),
    io      = require('socket.io').listen(server);

app.get("/execute", function (req, res) {
    // connect to local socket server
    var localSock = net.createConnection("10000","127.0.0.1");
    localSock.setEncoding('utf8');

    localSock.on('data', function(data) {
        // send returned results from local socket server to all clients
        do stuff here to data ...
        send data to all connected clients view socketio socket...
        var dataToSend = data;
        localSock.end();

    }).on('connect', function(data) {
        // send GET data to local socket server to execute
        var command = req.query["command"];
        localSock.write(command);   
});

app.get (..., function() {});

app.get (..., function() {});

server.listen('3000');

io.on('connection', function(client) {
    client.broadcast.send(dataToSend);
});
4

2 に答える 2

1

グローバル ソケット オブジェクトは として参照されio.socketsます。したがって、グローバルにブロードキャストするには、データを渡すだけio.sockets.emit()で、名前空間に関係なくすべてのクライアントに送信されます。

あなたが意図したと仮定して、あなたが投稿したコードio.sockets.on

io.on('connection', function(client) {
    client.broadcast.send(dataToSend);
});

任意の名前空間への任意の接続をリッスンし、dataToSend接続が確立されるとすべてのクライアントにブロードキャストします。あなたの主な目的はすべての人にデータを送信することであるため、グローバル名前空間を活用するだけですがio.sockets、コードで使用する方法は機能しません。

app.get('/execute', function (req, res) {
  var localSock = net.createConnection("10000","127.0.0.1");

  localSock.setEncoding('utf8');
  localSock.on('connect', function(data) {
    var command = req.query.command;
    localSock.write(command);   
  });
  localSock.on('data', function(data) {
    var dataToSend = data;
    localSock.end();
  });

});

コードのこの部分ではGET、パス上のリクエストを適切にリッスンして/executeいますが、ソケット ロジックが正しくありません。command接続時にすぐに書き込みを行っていますが、これは問題ありませんが、dataイベントはデータ ストリームが終了したことを意味すると想定しています。ストリームには event があるため、イベントendで応答を収集し、data最後に のデータで何かを行う必要がありendます。

たとえば、サーバーが文字列This is a string that is being streamed.を送信し、次を使用する場合:

localSock.on('data', function(data) {
  var dataToSend = data;
  localSock.end();
});

を受信This is a striしただけで、ソケットを時期尚早に閉じてしまう可能性がありますend()。代わりに、次のようにします。

var dataToSend = [];

localSock.on('data', function(data) {
  dataToSend.push(data);
});
localSock.on('end', function() {
  dataToSend = dataToSend.join('');
  io.sockets.emit(dataToSend);
});

この場合、end()削除サーバーが独自のFINパケットを送信するため、使用する必要がないことに注意してください。

net.Socket返されるデータは ですReadable Stream。つまり、dataイベントをリッスンすると、データは、イベントが発生するまで収集する必要がある完全な応答の断片である可能性がありますendsocket.ioサーバーにメッセージを送信する場合は、代わりsocket.io-clientに socket.io 独自のクライアントを使用できます。

于 2013-05-03T21:18:32.657 に答える
0

これは、非常に人気のあるwebtutorialのコードです。Express 3.x を使用するためにいくつかの変更が行われました。

app.js のコードは次のとおりです。

 var express = require('express')
  , http = require('http');

var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);

server.listen(8000);
// routing
app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

// usernames which are currently connected to the chat
var usernames = {};

io.sockets.on('connection', function (socket) {

    // when the client emits 'sendchat', this listens and executes
    socket.on('sendchat', function (data) {
        // we tell the client to execute 'updatechat' with 2 parameters
        io.sockets.emit('updatechat', socket.username, data);
    });

    // when the client emits 'adduser', this listens and executes
    socket.on('adduser', function(username){
        // we store the username in the socket session for this client
        socket.username = username;
        // add the client's username to the global list
        usernames[username] = username;
        // echo to client they've connected
        socket.emit('updatechat', 'SERVER', 'you have connected');
        // echo globally (all clients) that a person has connected
        socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
        // update the list of users in chat, client-side
        io.sockets.emit('updateusers', usernames);
    });

    // when the user disconnects.. perform this
    socket.on('disconnect', function(){
        // remove the username from global usernames list
        delete usernames[socket.username];
        // update list of users in chat, client-side
        io.sockets.emit('updateusers', usernames);
        // echo globally that this client has left
        socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
    });
});

上記のコードは Webtutorial と同じコードですが、Riwels の回答を使用して Express 3.x 用にいくつかの変更が加えられています。

index.html のコードは次のとおりです。

 <script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
    var socket = io.connect('http://localhost:8000');

    // on connection to server, ask for user's name with an anonymous callback
    socket.on('connect', function(){
        // call the server-side function 'adduser' and send one parameter (value of prompt)
        socket.emit('adduser', prompt("What's your name?"));
    });

    // listener, whenever the server emits 'updatechat', this updates the chat body
    socket.on('updatechat', function (username, data) {
        $('#conversation').append('<b>'+username + ':</b> ' + data + '<br>');
    });

    // listener, whenever the server emits 'updateusers', this updates the username list
    socket.on('updateusers', function(data) {
        $('#users').empty();
        $.each(data, function(key, value) {
            $('#users').append('<div>' + key + '</div>');
        });
    });

    // on load of page
    $(function(){
        // when the client clicks SEND
        $('#datasend').click( function() {
            var message = $('#data').val();
            $('#data').val('');
            // tell server to execute 'sendchat' and send along one parameter
            socket.emit('sendchat', message);
        });

        // when the client hits ENTER on their keyboard
        $('#data').keypress(function(e) {
            if(e.which == 13) {
                $(this).blur();
                $('#datasend').focus().click();
            }
        });
    });

</script>
<div style="float:left;width:100px;border-right:1px solid black;height:300px;padding:10px;overflow:scroll-y;">
    <b>USERS</b>
    <div id="users"></div>
</div>
<div style="float:left;width:300px;height:250px;overflow:scroll-y;padding:10px;">
    <div id="conversation"></div>
    <input id="data" style="width:200px;" />
    <input type="button" id="datasend" value="send" />
</div>
于 2013-05-03T20:35:59.917 に答える