Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Echo WebSocket in Dart

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?

like image 416
Mattia Avatar asked Sep 30 '18 17:09

Mattia


People also ask

What is Echo WebSocket?

echo.websocket.org provides a webSocket server that lets you make a webSocket connection to it and then it simply echos back to you anything that you send it. It's there primarily for testing and demo purposes.

How do I make a dart WebSocket server?

To use a WebSocket in your web app, first create a WebSocket object, passing the WebSocket URL as an argument to the constructor. var webSocket = new WebSocket('ws://127.0.0.1:1337/ws'); To send data on the WebSocket, use the send method. To receive data on the WebSocket, register a listener for message events.

Can you ping a WebSocket?

Pings and Pongs: The Heartbeat of WebSockets At any point after the handshake, either the client or the server can choose to send a ping to the other party.


1 Answers

I managed to do that, actually I was totally on the wrong path, here is the actual way to do it:

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');
  });
}
like image 93
Mattia Avatar answered Sep 25 '22 15:09

Mattia