1

我有以下客户端代码:

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 没有被触发。我怀疑我错过了一些东西,但不确定是什么。

4

1 回答 1

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类似于客户端的实例。

于 2014-01-05T10:18:15.493 回答