I am new to Dart Development and I am having a problem about concurrency. I am trying to understand Socket.io. I followed the Socket.io tutorial on its website and now trying to build my code in Dart.
I implemented these 2 files
server.dart
import "package:socket_io/socket_io.dart";
void main(List<String> args) {
Server io = Server();
io.on("connect", (client) {
print("Connection occurred");
client.on("msg", (data) {
print("Message received: $data");
});
});
io.listen(3000);
print("Socket IO server running on port 3000");
}
client.dart
import 'dart:io';
import 'package:socket_io_client/socket_io_client.dart' as IO;
Future<void> main() async {
// Dart client
IO.Socket socket = IO.io('http://localhost:3000', <String, dynamic>{
'transports': ['websocket'],
'autoConnect': false,
});
socket.connect();
for(int a = 0; a < 4; a++){
String? name = stdin.readLineSync();
if(name! == "add"){
socket.emit("msg", "A MESSAGE");
}
}
}
pubsec.yaml dependencies
dependencies:
flutter:
sdk: flutter
web_socket_channel: ^2.1.0
cupertino_icons: ^1.0.6
ansicolor: ^2.0.2
socket_io_client: ^1.0.0
socket_io: ^1.0.1
flutter_js: ^0.8.1
I first start the server.dart and then client.dart. In the client.dart my expectation is whenever I type add in the terminal I will receive **message received: A MESSAGE ** immediately. Instead program waits for the end of the for loop and the prints **message received: A MESSAGE ** on the server terminal. Why this is happening.
I think for loop blocks the whole flow of the client program but I already connected the server with socket.connect. But i did not understand why it is blocking.