我是 node.js 和 socket.io 场景的新手,所以这可能是一个简单的修复......但这里有。我有以下 POC 用于通过 UDP 接收消息并将它们回显到浏览器。在 55555 上接收到 UDP 消息,执行 websocket 写入,客户端在其浏览器中看到数据。但是,当另一个客户端连接到服务器时,在接收到数据报时会执行四次 websocket 写入 - 我相信每个客户端两次,因为附加的数据现在显示了两次。启动第三个客户端显示六次 websocket 写入 - 附加数据现在出现三次。
任何想法是什么原因造成的?愚蠢的错误?误解?漏洞?
服务器:
var dgram = require("dgram");
var udpserver = dgram.createSocket("udp4");
udpserver.bind(55555); //udp listener
var express = require("express");
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(12345); //tcp http listener
io.sockets.on('connection', function (socket) {
udpserver.on('message', function (msg, rinfo) {
io.sockets.emit('update', msg.toString());
});
});
客户:
<!DOCTYPE HTML>
<script src="http://code.jquery.com/jquery-1.8.1.min.js"></script>
<script src="http://localhost:12345/socket.io/socket.io.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var socket = new io.connect('http://localhost:12345');
socket.on('update', function (data) {
$("#stuff").append(data + "<br>");
});
});
</script>
<div id=stuff></div>
</html>
node
以下是显示第一个客户端连接后和第二个客户端连接后发送的数据的一些输出:
info - socket.io started
debug - served static content /socket.io.js
debug - client authorized
info - handshake authorized xrMZtzv9HPSngRYzMibw
debug - setting request GET /socket.io/1/websocket/xrMZtzv9HPSngRYzMibw
debug - set heartbeat interval for client xrMZtzv9HPSngRYzMibw
debug - client authorized for
debug - websocket writing 1::
debug - websocket writing 5:::{"name":"update","args":["test1\n"]}
debug - emitting heartbeat for client xrMZtzv9HPSngRYzMibw
debug - websocket writing 2::
debug - set heartbeat timeout for client xrMZtzv9HPSngRYzMibw
debug - got heartbeat packet
debug - cleared heartbeat timeout for client xrMZtzv9HPSngRYzMibw
debug - set heartbeat interval for client xrMZtzv9HPSngRYzMibw
debug - served static content /socket.io.js
debug - client authorized
info - handshake authorized VJKxI4y8TV9tcYjEMibx
debug - setting request GET /socket.io/1/websocket/VJKxI4y8TV9tcYjEMibx
debug - set heartbeat interval for client VJKxI4y8TV9tcYjEMibx
debug - client authorized for
debug - websocket writing 1::
debug - websocket writing 5:::{"name":"update","args":["test1\n"]}
debug - websocket writing 5:::{"name":"update","args":["test1\n"]}
debug - websocket writing 5:::{"name":"update","args":["test1\n"]}
debug - websocket writing 5:::{"name":"update","args":["test1\n"]}