2017-09-01 86 views
1

我要当一个REST API称为数据推送到网络插座通过触发外部

我有一个基于明确节点JS应用程序将数据推送到所有连接的插座。

在应用程序启动时,我创建了文档中提到的套接字服务器。

客户端代码

var socket = io('http://localhost'); 
socket.emit('client_id', 'test'); 
socket.on('message', function (message) { 
    console.log(message); 
}); 

服务器代码

io.on('connection', function (socket) { 
    socket.on('client_id', function (client_id) { 
     socket.join(client_id); 
    }); 
}); 

API调用

io.sockets.to('client_name').emit('message', 'Some message'); 

这个问题我s,这工作正常,当我启动节点/套接字服务器并启动客户端。

但是,当我重新启动节点/套接字服务器时,客户端不再接收消息。我将不得不重新加载客户端以开始接收消息。

可能是什么问题

+0

你能提供你的客户端代码吗?您是使用'socket.io'客户端还是[WebSocket API](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket)? – codtex

+0

正如我所提到的,无论在文档中提到什么。任何方式..只是更新 – madhairsilence

+0

当我在两侧使用'socket.io'库,当我停止服务器并再次运行时,所有客户端自动连接。问题可能来自应用程序设计。 – codtex

回答

2

所以在commented的问题下,我会尝试解释你提供的代码究竟发生了什么。此外,我想了一个办法,提出你your comment

// With the following line of code you connect to the server 
var socket = io('http://localhost'); 

// Now you send the client_id and it is sent only once per page load 
socket.emit('client_id', 'test'); 

// And here subscribe to the message event 
socket.on('message', function (message) { 
    console.log(message); 
}); 

// ---------------------------------------- 
// now we change the above code like 

var socket = io('http://localhost'); 
socket.on('connect', function(){ 
    // emit the event client_id every time you connect 
    socket.emit('client_id', 'test'); 
    socket.on('message', function (message) { 
     console.log(message); 
    }); 
}); 

您需要包装内on('connect', ...)申购代码,以确保每一个你连接到服务器client_id时间被发送。否则当客户端代码被加载时,client_id只发送一次。

如果你想避免双重信息,如your comment所述,您可以更新服务器端代码,如:

// Save reference to client_id by socket.id 
var clientIds = {}; 
io.on('connection', function (socket) { 

    socket.on('client_id', function (client_id) { 
     clientIds[socket.id] = client_id; 
     socket.join(client_id); 
    }); 

    // Subscribe to disconnect event and leave the room once client is disconnected 
    socket.on('disconnect', function (reason) { 
     // leave the room 
     socket.leave(clientIds[socket.id]); 
    }); 

}); 

与上面的代码,你确保你离开房间,一旦一个客户端断开连接。

让我知道如果有什么不清楚。祝你好运!

+0

这清除了事情。非常感谢。总结一下。 1.将代码置于'连接'内,2.在页面刷新期间使用'socket.id'手动删除连接,以避免连接重复; – madhairsilence

+0

不客气,朋友。我很高兴这是有帮助的:) – codtex

-2

每个网络连接都有一个与之相关的一些状态,当你重新启动服务器,你最有可能失去。实现超时并重新连接到服务器是一种可能的解决方案。