0
我已經設置了服務器,現在我只想每60秒發送一條消息。如何在其他功能中發送消息?我想寫一些像函數gameLoop(){someobject.send(myMessage); }但如果是這種情況,那麼someobject.send(myMessage)會是什麼?通過websocket在定時器上發送消息
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(3001, function() {
console.log((new Date()) + ' Server is listening on port 3001');
});
wsServer = new WebSocketServer({
httpServer: server,
// You should not use autoAcceptConnections for production applications
autoAcceptConnections: false
});
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var connection = request.accept('echo-protocol', request.origin);
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
if(message.utf8Data == "Map?") {
connection.send(JSON.stringify(map));
}
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});
我的IDE是說global.wsServer.sendMessage()是一個未解決的函數或方法。 –
是否在創建'var wsServer = new WebSocketServer({...})後設置了'global.wsServer = wsServer'' – Nivesh
將代碼添加到代碼後,我現在得到:TypeError:undefined不是函數.send()函數。我正在使用websocket v1.0.22包。 –