Search code examples
websocketdartdart-async

How can I ensure the writable flag is true before send()?


I am creating an abstraction layer for Dart WebSocket who is also protocol compatible with Socket.IO, but it has a problem I can not solve.

The follow code convert the HttpRequest into a WebSocket and save the socket instance on the Transport... Here you can see I change the value of the writable flag to true in order to inform the socket is open.

WebSocketTransformer.upgrade(req).then((socket) {
  this._socket = socket;
  this.writable = true;

  this._socket.handleError(() {
    this.onClose();
  });

  // start listen the socket;
  socket.listen((packet) {
    this.onData(packet);
  });
}).catchError((Exception e) {
  this.onError('Can\'t conenct with the socket.', e.toString());
});

(The full code can be founded here.)

When I debug the code first the debugger stops inside that closure and only then stops here, where the check is make but writable still false :/

void flush([_]) {
  if (this._readyState != SocketStates.closed && this.transport.writable &&
      !this._writeBuffer.isEmpty) {

(The full code can be founded here) I really need help...


Solution

  • Your constructor makes an async call but doesn't return a future (not possible in a constructor)

    WebSocketTransformer.upgrade(req).then
    

    Use a static method instead which returns Future<WebSocketTransformer> or use an init method where you initiaize your class after creation. There might be other problems but yor code does not show how you use your class therefore its hard to tell.