felangel / web_socket_client

A simple WebSocket client for Dart which includes automatic reconnection logic.
https://pub.dev/packages/web_socket_client
MIT License
150 stars 32 forks source link

Error: When the server sends a message or receives a message, the connection is being disrupted. #22

Closed hasancaktar closed 7 months ago

hasancaktar commented 1 year ago

I am trying to connect a Flutter application to a server that I developed in .NET Core. After establishing the connection, the application disconnects when it receives a message. I have been unable to find a solution. When I connect to the server using Postman, Hercules, or other client applications, there are no issues. However, I cannot establish a connection with this package.

There may be a mismatch during the handshake process. It is possible that the header is not coming correctly due to the parsing structure ("\r\n"). Error: HttpException (HttpException: Invalid request method, uri = http://localhost:8080) Below is a simple example of the server application and a code snippet for a basic client in Flutter:

Server code:

using XiaoFeng.Net;

namespace AppserverTest
{
    internal class Program
    {
        static NetServer<ServerSession> server8080 = new NetServer<ServerSession>(8080);

        static void Main(string[] args)
        {
            server8080.OnStart += Server8080_OnStart;
            server8080.OnStop += Server8080_OnStop;
            server8080.OnDisconnected += Server8080_OnDisconnected;
            server8080.OnNewConnection += Server8080_OnNewConnection;
            server8080.OnMessage += Server8080_OnMessage;

            server8080.Start();
            Console.ReadLine();
        }

        private static void Server8080_OnStop(ISocket socket, EventArgs e)
        {
            Console.WriteLine("8080 stopped");
        }

        private static void Server8080_OnStart(ISocket socket, EventArgs e)
        {
            Console.WriteLine("8080 started");
        }

        private static void Server8080_OnMessage(INetSession session, string message, EventArgs e)
        {
            Console.WriteLine(message);
            session.Send("Hello");
        }

        private static void Server8080_OnNewConnection(INetSession session, EventArgs e)
        {
            Console.WriteLine("connected: " + session.Headers);
            session.Send("hello");
        }

        private static void Server8080_OnDisconnected(INetSession session, EventArgs e)
        {
            Console.WriteLine("8080 disconnected");
        }
    }
}

Client:

import 'package:web_socket_client/web_socket_client.dart';

void main() async {
  final uri = Uri.parse('ws://127.0.0.1:8080');
  const backoff = ConstantBackoff(Duration(seconds: 1));
  final socket = WebSocket(uri, backoff: backoff);

  socket.connection.listen((state) => print('state: "$state"'));

  socket.messages.listen((message) {
    print('message: "$message"');
    socket.send("hi server");
  });
}

Please note that the provided code snippets are for reference purposes, and the issue you are facing may require further analysis and debugging.

danielmeza commented 1 year ago

try to prevent the app to exit from the main loop, you can use Future.delayed and wait infinity.

felangel commented 7 months ago

Closing for now since there aren't any actionable next steps. Please file a new issue if this is still a problem and please include a link to a minimal reproduction sample, thanks!

ebwood commented 7 months ago

code after socket.messages.listen never run:

server.dart

import 'dart:io';

void main() async {
  HttpServer server = await HttpServer.bind(InternetAddress.anyIPv4, 8080);
  print('WebSocket server running on port 8080');

  server.listen((HttpRequest request) {
    if (WebSocketTransformer.isUpgradeRequest(request)) {
      WebSocketTransformer.upgrade(request).then((WebSocket websocket) {
        print('Client connected: ${websocket.hashCode}');
        // websocket.add('hello you!!!');

        websocket.pingInterval = Duration(seconds: 5);
        websocket.listen((message) {
          print('Received message: $message');
          websocket.add(message);
        });

        websocket.done.then((value) {
          print('Client disconnected: ${websocket.hashCode}');
        });
      });
    } else {
      request.response.write('hello http request');
      request.response.close();
    }
  });
}

client.dart

import 'package:web_socket_client/web_socket_client.dart';

void main() async {
  // Create a WebSocket client.
  final uri = Uri.parse('ws://localhost:8080');
  const backoff = ConstantBackoff(Duration(seconds: 5));
  final socket =
      WebSocket(uri, backoff: backoff, pingInterval: Duration(seconds: 25));

  // Listen for changes in the connection state.
  socket.connection.listen((state) => print('state: "$state"'));

  // Listen for incoming messages.
  socket.messages.listen((message) {
    print('received message from server: "$message"');
  });

  socket.send('hello to server');
}

the last line socket.send('hello to server') never run.