我有以下客户端代码:
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没有被触发。我怀疑我错过了什么,但不确定是什么。
答案 0 :(得分:2)
是的,你遗漏了一些东西,完整的服务器端实现。 ServerSocket
只是用于TCP(或UDP)的普通套接字。
但是websocket需要一个HTTP服务器,它处理HTTP请求并升级到Websocket连接的连接:
import 'dart:io';
void main() {
HttpServer.bind('127.0.0.1', port)
.then((HttpServer server) {
print('listening for connections on $port');
server.listen((HttpRequest request) {
if (request.uri.path == '/ws') {
WebSocketTransformer.upgrade(request).then((WebSocket websocket) {
websocket.listen((message) => print('Message from client'));
print('Client connected');
});
} else {
/* ... */
}
});
},
onError: (error) => print("Error starting HTTP server: $error"));
}
来自SethLadd的简单示例。但在升级到websocket之前,我可能还会检查请求CONNECTION
和UPGRADE
标头是否正确。升级连接后,您有一个Websocket
实例,类似于客户端上的实例。