我想提供一个有意义的错误给客户当太多用户连接或当他们从一个不域连接的连接,所以......+的NodeJS的WebSockets - 拒绝与消息
我写的一些WebSocket的服务器代码:
var http = require('http');
var httpServer = http.createServer(function (request, response)
{
// i see this if i hit http://localhost:8001/
response.end('go away');
});
httpServer.listen(8001);
// https://github.com/Worlize/WebSocket-Node/wiki/Documentation
var webSocket = require('websocket');
var webSocketServer = new webSocket.server({ 'httpServer': httpServer });
webSocketServer.on('request', function (request)
{
var connection = request.reject(102, 'gtfo');
});
而且一些的WebSocket客户端代码:
var connection = new WebSocket('ws://127.0.0.1:8001');
connection.onopen = function (openEvent)
{
alert('onopen');
console.log(openEvent);
};
connection.onclose = function (closeEvent)
{
alert('onclose');
console.log(closeEvent);
}
connection.onerror = function (errorEvent)
{
alert('onerror');
console.log(errorEvent);
};
connection.onmessage = function (messageEvent)
{
alert('onmessage');
console.log(messageEvent);
};
我得到的是alert('onclose');
与CloseEvent
对象记录到控制台没有任何状态代码或消息,我可以找到。当我通过ws://localhost:8001
连接时,httpServer回调不起作用,所以我无法在那里捕捉到它。 RFC建议当出现问题时,我应该能够发送除101以外的任何状态代码,但Chrome会在控制台Unexpected response code: 102
中引发错误。如果我打电话给request.reject(101, 'gtfo')
,暗示它成功了,我就会得到一个握手错误,就像我所期望的那样。
不太确定我还能做些什么。在Chrome的WebSocket实现中获取服务器响应现在是不可能的吗?
ETA:这里是一个非常讨厌的黑客,我希望这不是我最终要做的。
var connection = request.accept(null, request.origin);
connection.sendUTF('gtfo');
connection.close();
网址ws://127.0.0.1:8001是否与提供网页的网址匹配? – akonsu
我的意思是包含客户端代码的页面。 – akonsu
@akonsu意思是它在同一个域名?不,我在本地运行它file:///,这不是一个问题,因为我没有验证'request.origin'。 – Langdon