C# WPF Socket gets disconnected automatically. Why?


I am working on one project that allows clients and server communicate asynchronous. Everything works perfectly fine. But by some reason if client is online for 10 or 15 minutes, it gets forcefully disconnected by the host. And it happens when I am trying to send a string to the server after 10 or 15 minutes.

Client Log file:

System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult) at TalkCentre.Main.<>c__DisplayClass31_0.b__0()

System.ObjectDisposedException: Cannot access a disposed object. Object name: 'System.Net.Sockets.Socket'. at System.Net.Sockets.Socket.Send(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, SocketError& errorCode) at System.Net.Sockets.Socket.Send(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) at TalkCentre.Main.SendString(String text)

Server Log File:

System.Net.Sockets.SocketException (0x80004005): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult) at TalkCentreServer.Program.ReceiveCallback(IAsyncResult AR)

When I make exception, it looks like it appears in this code in SERVER:

    private static void ReceiveCallback(IAsyncResult AR)
        Socket current = (Socket)AR.AsyncState;
        int received;
            received = current.EndReceive(AR);
        catch (SocketException)
            Console.WriteLine(current.RemoteEndPoint + " Client forcefully disconnected");
            // Don't shutdown because the socket may be disposed and its disconnected anyway.
        byte[] recBuf = new byte[received];
        Array.Copy(buffer, recBuf, received);
        string text = Encoding.ASCII.GetString(recBuf);
        if (text.ToLower() == "connected") // Client requested time
            foreach (Socket connectedUsers in clientSockets)
                string _eachConnection = ("Connected- " + current.RemoteEndPoint).ToString();
                byte[] data = Encoding.ASCII.GetBytes(_eachConnection);
                Socket socket = (Socket)connectedUsers;
                Console.WriteLine(socket.RemoteEndPoint + " Is Online");
        current.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current);

I am pretty sure that it is not a duplicate as this issue is C# WPF related. And this issue doesn't occur when trying to connect. But only after 10 or 15 minutes when sending string.

asked on Stack Overflow Jun 7, 2020 by XtaXCraft • edited Jun 7, 2020 by Clemens

0 Answers

Nobody has answered this question yet.

User contributions licensed under CC BY-SA 3.0