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?
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.
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.
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.
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');
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With