我想提供一個有意義的錯誤給客戶當太多用戶連接或當他們從一個不域連接的連接,所以......+的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