GithubHelp home page GithubHelp logo

Comments (17)

jchristn avatar jchristn commented on June 11, 2024

Where in your code are you instantiating the client in the server? Can you paste some sample code to reproduce the issue?

from supersimpletcp.

saklanmazozgur avatar saklanmazozgur commented on June 11, 2024

I wrote a code for testing. Please excuse it for being crowded.

`    private async void Server_Clicked(object sender, EventArgs e)
    {
        try
        {
            if (simpleTcpServer == null)
            {
                simpleTcpServer = new SimpleTcpServer(ServerIpAddress.Text, Convert.ToInt32(ServerPort.Text));
                simpleTcpServer.Events.ClientConnected += Events_ClientConnected;
                simpleTcpServer.Events.ClientDisconnected += Events_ClientDisconnected;
                simpleTcpServer.Events.DataReceived += Events_DataReceived;
                simpleTcpServer.Start();
            }
            else
            {
                if (ServerConnectBt.Text == "Close")
                {
                    simpleTcpServer.Events.ClientConnected -= Events_ClientConnected;
                    simpleTcpServer.Events.ClientDisconnected -= Events_ClientDisconnected;
                    simpleTcpServer.Events.DataReceived -= Events_DataReceived;
                    simpleTcpServer.Stop();
                }
                else
                {
                    simpleTcpServer = new SimpleTcpServer(ServerIpAddress.Text, Convert.ToInt32(ServerPort.Text));
                    simpleTcpServer.Events.ClientConnected += Events_ClientConnected;
                    simpleTcpServer.Events.ClientDisconnected += Events_ClientDisconnected;
                    simpleTcpServer.Events.DataReceived += Events_DataReceived;
                    simpleTcpServer.Start();
                }
            }

            if (simpleTcpServer.IsListening == true)
                ServerConnectBt.Text = "Close";
            else
                ServerConnectBt.Text = "Open";
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }`

When I tried the same code and the same version of supersimpletcp in .net framework 4.7.2, it connected smoothly and there was no disconnection problem.

On the client side, I used programs such as Hercules and Docklight, which I use constantly for connection, which I am sure is not a problem. Additionally, I wrote a simple example, they all have the same problem.

`private void Client_Click(object sender, EventArgs e)
    {
        simpleTcpClient = new SimpleTcpClient(ClientIpAddress.Text, Convert.ToInt32(ClientPort.Text));
        simpleTcpClient.Connect();
        simpleTcpClient.Send("Hello");
    }`

from supersimpletcp.

jchristn avatar jchristn commented on June 11, 2024

It is most certainly getting disposed when the event handler exits. You might want to instantiate outside of your event handlers.

from supersimpletcp.

saklanmazozgur avatar saklanmazozgur commented on June 11, 2024

It is most certainly getting disposed when the event handler exits. You might want to instantiate outside of your event handlers.

Unfortunately, I didn't understand what you mean.

from supersimpletcp.

jchristn avatar jchristn commented on June 11, 2024

You should define your server, and client instances in the main form code itself, or in the backing app class. If you define and instantiate inside of your event handler, it is going to get disposed when the event is done being processed.

from supersimpletcp.

saklanmazozgur avatar saklanmazozgur commented on June 11, 2024

I guess I didn't convey the problem correctly. The code works on .net 4.7.2 and there is no problem. Exactly the same code. It is already defined outside the TcpServer click event. Therefore, there is no problem due to the reason you mentioned. Additionally, when the Client wants to establish a connection, the relevant event is triggered, but the disconnected event is also triggered immediately.

from supersimpletcp.

saklanmazozgur avatar saklanmazozgur commented on June 11, 2024

To put it more simply;

Server code is taken directly from the sample code.

    SimpleTcpServer server;
    private void InitializeServer()
    {
        server = new SimpleTcpServer("10.0.2.16:5001");
        server.Events.ClientConnected += ClientConnected;
        server.Events.ClientDisconnected += ClientDisconnected;
        server.Events.DataReceived += DataReceived;
        server.Start();
    }

Client Code is as follows. However, regardless of this code, other applications already disconnect at the moment of connection.

    SimpleTcpClient simpleTcpClient;
    private void Client_Click(object sender, EventArgs e)
    {
        simpleTcpClient = new SimpleTcpClient("10.0.2.16", 5001);
        simpleTcpClient.Connect();
        simpleTcpClient.Send("Hello");
    }

I open the server. It opens without any problems. I am connecting via client. ClientConnected event is triggered. ClientDisconnected is triggered without taking any action. No data is received in DataReceived.

from supersimpletcp.

saklanmazozgur avatar saklanmazozgur commented on June 11, 2024

I think the problem may be in the library. Since I wasn't sure if the problem was on the Android side, I wrote a simple listener. I did not experience any problems like the ones below. There is no break on the client side.

    private async Task ServerStart()
    {

        TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Any, 20000));
        listener.Start();

        Console.WriteLine("The server has been started. Waiting for connection...");

        while (true)
        {
            TcpClient client = await listener.AcceptTcpClientAsync();
            _ = HandleClientAsync(client);
        }
    }

    static async Task HandleClientAsync(TcpClient client)
    {
        try
        {
            using (NetworkStream stream = client.GetStream())
            {
                byte[] buffer = new byte[1024];
                int bytesRead;

                while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                {
                    string receivedData = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                    Console.WriteLine($"Data from Client: {receivedData}");
                    byte[] sendData = Encoding.UTF8.GetBytes(receivedData);
                    await stream.WriteAsync(sendData, 0, sendData.Length);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
        finally
        {
            client.Close();
            Console.WriteLine("The connection has been closed.");
        }
    }

from supersimpletcp.

jchristn avatar jchristn commented on June 11, 2024

Hi @saklanmazozgur thanks for the explanation, and sorry for the miscommunication and misunderstanding on my part.

Can you try using an unawaited task instead of _? I wonder if it's being garbage collected. Perhaps Task unawaited = Task.Run(() => ... )?

I'm away from my workstation for the next two days but can dig into this deeper when I return. Cheers

from supersimpletcp.

jchristn avatar jchristn commented on June 11, 2024

Or even define a List or Dictionary<Guid, Task> outside of the ServerStart method and manage it that way? It seems like garbage collection is happening here.

from supersimpletcp.

saklanmazozgur avatar saklanmazozgur commented on June 11, 2024

Can you try using an unawaited task instead of _? I wonder if it's being garbage collected. Perhaps Task unawaited = Task.Run(() => ... )?

I'll try it tonight and let you know. Thank you for helping.

from supersimpletcp.

saklanmazozgur avatar saklanmazozgur commented on June 11, 2024

Or even define a List or Dictionary<Guid, Task> outside of the ServerStart method and manage it that way? It seems like garbage collection is happening here.

I will add the connecting clients to a list and communicate with them. I tried as you mentioned in the previous comment, but the result is the same. Why is the connecting client instantly collected by the garbage collector?

What I don't understand is why it works in .net 4.7.2 but not in Maui. What is the difference?

from supersimpletcp.

saklanmazozgur avatar saklanmazozgur commented on June 11, 2024

What I don't understand is why it works in .net 4.7.2 but not in Maui. What is the difference?

Something came to my mind that would cause this. Android does not allow a feature that SuperSimpleTcp wants to access as soon as the client connects, causing it to fall into this catch. When it falls into catch, the client is already disposed. I haven't had the opportunity to do detailed research yet to understand the source of the problem.

from supersimpletcp.

saklanmazozgur avatar saklanmazozgur commented on June 11, 2024

As I guessed;

The code snippet below within the IsClientConnected function fails and the client connection is disconnected.

            var state = IPGlobalProperties.GetIPGlobalProperties()
                .GetActiveTcpConnections()
                    .FirstOrDefault(x =>
                        x.LocalEndPoint.Equals(client.Client.LocalEndPoint)
                        && x.RemoteEndPoint.Equals(client.Client.RemoteEndPoint));

System.PlatformNotSupportedException: 'Operation is not supported on this platform.'

As a workaround, I added a check like below. I don't know if it is supported on iOS. It's probably not supported.

        private bool IsClientConnected(TcpClient client)
        {
            if (client == null) return false;

            DevicePlatform platform = DeviceInfo.Platform;
            if (platform != DevicePlatform.Android && platform != DevicePlatform.iOS)
            {
                var state = IPGlobalProperties.GetIPGlobalProperties()
               .GetActiveTcpConnections()
                   .FirstOrDefault(x =>
                       x.LocalEndPoint.Equals(client.Client.LocalEndPoint)
                       && x.RemoteEndPoint.Equals(client.Client.RemoteEndPoint));

                if (state == default(TcpConnectionInformation)
                    || state.State == TcpState.Unknown
                    || state.State == TcpState.FinWait1
                    || state.State == TcpState.FinWait2
                    || state.State == TcpState.Closed
                    || state.State == TcpState.Closing
                    || state.State == TcpState.CloseWait)
                {
                    return false;
                }
            }

            if ((client.Client.Poll(0, SelectMode.SelectWrite)) && (!client.Client.Poll(0, SelectMode.SelectError)))
            {
                byte[] buffer = new byte[1];
                if (client.Client.Receive(buffer, SocketFlags.Peek) == 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }

            return false;
        }

from supersimpletcp.

saklanmazozgur avatar saklanmazozgur commented on June 11, 2024

A detailed review may be needed for Android and IOS. I haven't used all the features yet. Maybe there are still unsupported features somewhere.

from supersimpletcp.

jchristn avatar jchristn commented on June 11, 2024

Nice catch. I'm happy to take a PR on this if you have time to put one together!

from supersimpletcp.

saklanmazozgur avatar saklanmazozgur commented on June 11, 2024

I will send a PR tomorrow when I am available. Thanks.

from supersimpletcp.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.