Client does not receive message from socket server if server proactively sends the message first

40 Views Asked by At

I'm developing a chat feature for my Flutter app. My app has two modes: Client & Server.

  • On Server side, I'm using shelf, shelf_router, shelf_web_socket for hosting: (sorry, the code is not minimal, but the main stuff is here)
final routerHandler = shelf_router.Router()
      ..get('/files', (request) => _getFilesHandler(request, address))
      ..get('/message', (request) => handleWs(request))
      ..post('/upload', (request) => _uploadFileHandler(request, address));

// static handler always in the first order in list handlers
Cascade cascade = Cascade()
      .add(routerHandler)
var handler = const Pipeline()
    .addMiddleware(logRequests(logger: (message, isError) => _exposeLogger(message: message)))
    .addHandler(cascade.handler);
    
await shelf_io.serve(handler, ipAddress, port)
FutureOr<Response> handleWs(Request request) {
final channels = <WebSocketChannel>[];

return ws.webSocketHandler((WebSocketChannel channel) {
  channels.add(channel);
  channel.stream.listen((message) {
    try {
      final receivedMessage = Message.fromJson(json.decode(message));
      final updatedMessage = receivedMessage.copyWith(messageState: MessageState.sent);

      final response = json.encode(updatedMessage.toJson());
      for (final c in channels) {
        c.sink.add(response);
      }
    } catch (e) {
      debugPrint('Error while handling incoming message in socket: ${e.toString()}');
    }
  }, onDone: () => channels.remove(channel)
  );
})(request);
}
  • On Client side:
@override
void initState() {
super.initState();
    _handleSocket();
}

void _handleSocket() {
    _webSocketChannel = WebSocketChannel.connect(Uri.parse(endpoint));
    _webSocketChannel.stream.listen((response) {
      print('response from ws: $response');
    });
}
void _sendMessage() async {
    final data = json.encode(message.toJson());
    _webSocketChannel.sink.add(data);
}

When a client sends a message, server can receive it and response back to client with updated state in message

But when server proactively sends a message first, the client can't receive that message. Debugging this and seeing both connected to the same socket endpoint. Server can send and receive the message itself (server also uses the same chat UI as Client, so it listens to the socket itself too)

I wonder if there is a problem with Client or Server implementation here?

0

There are 0 best solutions below