我有以下客户端代码:
import 'dart:html';
import 'dart:async';
void main() {
WebSocket ws = new WebSocket('ws://127.0.0.1:4949');
ws.onOpen.listen((_) => print('open'));
ws.onMessage.listen((MessageEvent e) => print(e.data));
ws.onClose.listen((_) => print('closed'));
ws.onError.listen((_) => print('error'));
}
而这个服务器端代码:
import 'dart:io';
import 'dart:async';
main() {
ServerSocket.bind('127.0.0.1', 4949).then((ServerSocket server) {
server.listen((Socket client){
print('Connection from '
'${client.remoteAddress.address}:${client.remotePort}');
client.write('hello from server');
});
});
}
WebSocket 连接成功连接到 ServerSocket。服务器代码打印:
Connection from 127.0.0.1:55516
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: 127.0.0.1:4949
Origin: http://127.0.0.1:3030
Pragma: no-cache
Cache-Control: no-cache
Sec-WebSocket-Key: PrJr2iVElmEsX7ZItHnWHA==
Sec-WebSocket-Version: 13
Sec-WebSocket-Extensions: x-webkit-deflate-frame
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.39 (Dart) Safari/537.36
问题是 onOpen 和 onMessage 没有被触发。我怀疑我错过了一些东西,但不确定是什么。