当我尝试运行我的socket.io应用程序时,客户端上的socket.io只是使用新的和新的连接充斥服务器而不是维护一个:
代码很基本,所以可能出错?
requirejs(['http', 'socket.io', 'node-static],
function (Http, SocketIo, staticServer) {
const staticHTTP = new staticServer.Server('./');
var http = Http.createServer(function (request, response) {
request.addListener('end', function () {
staticHTTP.serve(request, response);
}).resume();
});
var io = SocketIo(http);
io.on('connection', function (socket) {
/// Handle connection
/// but socket IO keeps creating 5 connections per second
});
var port = process.env.PORT || 3000;
http.listen(port, function () {
console.log('listening on *:' + port);
});
});
requirejs(["socket.io"], function (io) {
var socket = io(location.hostname + ":" + location.port);
///These events never occur
socket.on("connect", function () {
console.log("Connected via websocket.");
})
socket.on("disconnect", function () {
console.warn("websocket ded")
});
})
答案 0 :(得分:1)
试试这个......
var socket = io({transports: ['websocket'], upgrade: false});
强制socket.io只使用webSocket并且从不使用HTTP轮询,然后问题就消失了。