握手正确完成,服务器可以解码来自客户端的数据,但当我尝试向客户端发送数据时,客户端会关闭连接。
我一直在使用http://websocket.org/echo.html作为客户端w.最新版本的火狐&铬。
这是我试图发送的数据帧:
129 10000001
4 100
116 1110100
101 1100101
115 1110011
116 1110100
-------
fin:true
opcode:1
len:4
masked:false
masks:[0, 0, 0, 0]
payload:test
?♦test
http://tools.ietf.org/html/rfc6455#section-5
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len | Extended payload length |
|I|S|S|S| (4) |A| (7) | (16/64) |
|N|V|V|V| |S| | (if payload len==126/127) |
| |1|2|3| |K| | |
+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
| Extended payload length continued, if payload len == 127 |
+ - - - - - - - - - - - - - - - +-------------------------------+
| |Masking-key, if MASK set to 1 |
+-------------------------------+-------------------------------+
| Masking-key (continued) | Payload Data |
+-------------------------------- - - - - - - - - - - - - - - - +
: Payload Data continued ... :
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
| Payload Data continued ... |
+---------------------------------------------------------------+
*/
以及负责向客户端发送数据的服务器端方法:
public void sendData(Socket socket, byte[] dataBytes){
System.out.println(java.util.Arrays.toString(dataBytes));
//[-127, 4, 116, 101, 115, 116]
for(byte b:dataBytes) System.out.println(Integer.toString((int)0xff&b,2));
/*
10000001
100
1110100
1100101
1110011
1110100
*/
try{
InputStream data = new ByteArrayInputStream(dataBytes);
OutputStream out = socket.getOutputStream();
//tested with ByteArrayOutputStream and written data == dataBytes
//out.write((byte)0x00); //tried with and without this
if ( data != null )
{
// tried also out.write(dataBytes) intstead of this
byte[] buff = new byte[2048];
while (true)
{
int read = data.read( buff, 0, 2048 );
if (read <= 0)
break;
out.write( buff, 0, read );
}
}
//out.write(-1);
//out.write((byte)0xFF);
out.flush();
//out.close();
if ( data != null )
data.close();
}catch(Exception e){
e.printStackTrace();
sockets.remove(socket);
}
}
一些问题:
- 在从服务器发送之前,是否等待连接完全打开
- 你能用wireshark捕捉流吗?看看电线上到底有什么
- 在Chrome的Javascript控制台中,您是否看到任何与WebSocket相关的错误
- 在Javascript websocket对象的onclose处理程序中,您能否console.log事件中的代码值和原因
像这样:
ws.onclose = function (e) {
console.log("closed - code " + e.code + ", reason " + reason);
}
您的问题(可能)是使用了旧协议。使用较新的。。。
@参见
http://web-sockets.org
具有客户端和服务器的工作源(Java)。