Echo WebSocket in Dart

2019-07-24 07:59发布

问题:

I'm trying to make an "echo" WebSocket in Dart, but online I could find only outdated examples.

This is my code at the moment:

server:

import 'dart:io';
import 'dart:convert';

void main() async {
  final serverSocket = await ServerSocket.bind('127.0.0.1', 5600);
  await for (Socket socket in serverSocket) {
    socket.transform(utf8.decoder).listen((data) {
      print(data);
    });
  }
}

client:

import 'dart:html';

WebSocket socket;
bool open = false;

void main() {
  querySelector('#sendHello').onClick.listen(onClick);
  querySelector('#output').text = 'Your Dart app is running.';

  socket = WebSocket('ws://localhost:5600');
  socket.onMessage.listen(socketMessage);
  socket.onOpen.listen((_) => open = true);
}

void socketMessage(MessageEvent event){
  print('I recived: ${event.data}');
}

void onClick(MouseEvent event) {
  if (!open)
    print('Connection is not open!');
  else
    socket.send('Hello');
}

The first text that is printed is:

GET / HTTP/1.1
Host: localhost:5600
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
Upgrade: websocket
Origin: http://localhost:63572
Sec-WebSocket-Version: 13
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,it;q=0.8,lb;q=0.7
Cookie: ....
Sec-WebSocket-Key: ...
Sec-WebSocket-Extensions: ...

then I'm unable to send/recive any more packets.

How can I make the ServerSocket working properly?

回答1:

I managed to do that, actually I was totally on the wrong way:

import 'dart:io';

void main() async {
  HttpServer server = await HttpServer.bind('localhost', 5600);
  server.transform(WebSocketTransformer()).listen(onWebSocketData);
}

void onWebSocketData(WebSocket client){
  client.listen((data) {
    client.add('Echo: $data');
  });
}