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事件意味着数据流已经结束。由于流有事件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,因为返回的数据是 a Readable Stream,这意味着,当你监听data事件时,数据可能是必须收集的完整响应的片段,直到end事件被触发。如果您要做的是将消息发送到socket.io服务器,那么您可以改用socket.io-clientsocket.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 中的代码相同,只是 Express 3.x 的一些更改是使用Riwels 的答案进行的

这是 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 回答