Pregunta

I have the following client-side code:

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'));
}

And this server-side code:

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');
    });
  });
}

The WebSocket connection connects successfully to the ServerSocket. The server code prints:

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

The problem is that the onOpen and onMessage do not get triggered. I suspect I'm missing something but not sure what.

¿Fue útil?

Solución

Yes you are missing something, the complete server side implementation. ServerSocket is just a plain socket used for TCP (or UDP).

But a websocket requires a HTTP server, that does the handling of the HTTP request and that upgrades the connection to a Websocket connection:

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"));
}

A simple example from SethLadd. But I would probably do also a check if the requests CONNECTION and UPGRADE headers are correct before upgrading to a websocket. After upgrading the connection you have a Websocket instance that is similar to the on one the client side.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top