我正在编写自己的脚本以使用 WebSocket API 使用 JavaScript 连接到 websocket 服务器。我在连接立即关闭时遇到问题。
这是客户端脚本:
var host = 'ws://localhost:8080';
try
{
debug.add('Connection request submitted for ' + host);
socket = new WebSocket(host);
debug.readyStateListener();
debug.add('Socket request started');
socket.onopen = function()
{
debug.add('Connection opened');
}
socket.onmessage = function(message)
{
debug.add('data received ' + message.data);
}
socket.onclose = function()
{
debug.add('Connection closed');
}
}
catch(e)
{
debug.add('WebSockets error ' + e.toString() );
}
这是我收到的调试:
Connection request submitted for ws://localhost:8080
socket readyState change to 0
Socket request started
socket readyState change to 3
Connection closed
debug.readyStateListener() 轮询 socket.readyState 以进行更改。发生的情况是它变为 0 表示连接正在打开,然后立即变为 3 表示连接已关闭。
服务器很好地接收到连接,但连接随后被客户端立即关闭。
我已经在启用 WebSockets 的 Opera 11 和最新版本的 Chrome 中进行了尝试。两次我得到相同的结果。
我可以通过原始连接与服务器完美通信,或者只需在浏览器中访问http://localhost:8080/,结果如下:
GET / HTTP/1.1
User-Agent: Opera/9.80 (Windows NT 6.1; U; IBM EVV/3.0/EAK01AG9/LE; en) Presto/2.9.168 Version/11.51
Host: localhost:8080
Accept: application/xhtml+voice+xml;version=1.2, application/x-xhtml+voice+xml;version=1.2, text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/webp, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1
Accept-Language: nl-NL,nl;q=0.9,en;q=0.8
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
通过 http 发送请求直到我结束它,连接也保持活动状态,没有任何缺陷。
服务器通过 JavaScript WebSocket API 接收此请求:
GET / HTTP/1.1
Host: localhost:8080
Origin: http://localhost
Upgrade: WebSocket
Sec-WebSocket-key1: L58(b Q]'9 4 9\ 0 *+ 6 a4
Connection: Upgrade
Sec-WebSocket-Key2: \+ 1 5d/9541840N*4
我最后的猜测是连接:升级或升级:客户端不正确支持 WebSocket。对我来说,接收 Connection: keep-alive 会更合乎逻辑,但我不知道如何重新爱上它。