none
An existing connection was forcibly closed by the remote host exception in Asynchronous C# socket RRS feed

  • Question

  • We are trying to develop a SOcket Server Program to which all GPS device will connect and This program will respond to them all. But there is an exception in BeginAccept Receive call which states that "An existing connection was forcibly closed by the remote host exception" while calling to BeginReceive Callback it throws this exception. We don't know what is exact problem, can you please help us? 

    Thank You.

    Code :

    using System;
    using System.Collections.Generic;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.IO;
    using System.Web;
    using DecodeGpsPacket;


    namespace GpsProtocol
    {
        class Server
        {
            private static readonly Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            private static readonly List<Socket> clientSockets = new List<Socket>();
            private const int BUFFER_SIZE = 2048;
            private const int PORT = 100;
            private static readonly byte[] buffer = new byte[BUFFER_SIZE];
            private static Dictionary<string, string> DevicesList = new Dictionary<string, string>();
            public static string Path = @"C:\Users\Shubham\Downloads\GpsProtocol\GpsProtocol\TextFile1.txt";

           

            static void Main()
            {
                Console.Title = "Server";
                SetupServer();
                Console.ReadLine(); 
                CloseAllSockets();
            }

            private static void SetupServer()
            {
                Console.WriteLine("Setting up server...");
                serverSocket.Bind(new IPEndPoint(IPAddress.Any, PORT));
                serverSocket.Listen(0);
                serverSocket.BeginAccept(AcceptCallback, null);
                Console.WriteLine("Server setup complete");
            }

         
            private static void CloseAllSockets()
            {
                foreach (Socket socket in clientSockets)
                {
                    socket.Shutdown(SocketShutdown.Both);
                    socket.Close();
                }

                serverSocket.Close();
            }

            private static void AcceptCallback(IAsyncResult AR)
            {
                Socket socket;

                try
                {
                    socket = serverSocket.EndAccept(AR);
                    Console.WriteLine("New Connection : {0} \n {1} \n==============", socket.RemoteEndPoint, DateTime.Now);
                }
                catch (ObjectDisposedException) // I cannot seem to avoid this (on exit when properly closing sockets)
                {
                    return;
                }

                clientSockets.Add(socket);
                socket.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, socket);
                Console.WriteLine("Client connected, waiting for request...");
                serverSocket.BeginAccept(AcceptCallback, null);
            }

            private static void ReceiveCallback(IAsyncResult AR)
            {
                Socket current = (Socket)AR.AsyncState;
                int received;

                try
                {
                    received = current.EndReceive(AR);
                }
                catch (SocketException)
                {
                    Console.WriteLine("Client forcefully disconnected");
                   
                    current.Close();
                    clientSockets.Remove(current);
                    return;
                }

                byte[] MainBuffer = new byte[received];
                Array.Copy(buffer, MainBuffer, received);

                try
                {
                    current.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current);
                }
                catch (Exception e)
                {
                    if (e.InnerException != null)
                    {
                        new SaveGpsInfo().LogException(e.Message, e.InnerException.Message, e.StackTrace);
                    }

                }
            }
        }
    }

    Thursday, November 2, 2017 9:55 AM

All replies

  • Unfortunately this is not something we're probably going to be of much use for. If the remote server dropped the connection then the issue is either on the remote side or with your configuration such that the remote side dropped the call. Since we have no knowledge of how the remote end works we cannot really assist here. I'd start by ideally trying to connect to the device outside your code perhaps using telnet or something. Once you've got that working you should have a pretty good idea of what configuration you'll need. You can then update your code to follow that. The documentation that came with your device should be able to tell you what it takes to communicate with the device. Most likely you need to do some sort of initialization handshaking. But only the device documentation would tell you that.

    Michael Taylor http://www.michaeltaylorp3.net

    Thursday, November 2, 2017 1:56 PM
    Moderator
  • thank you sir...but it was working fine till now but now it is throwing this exception..
    Friday, November 3, 2017 1:53 PM
  • Then you need to review what has changed in your code. A remote connection dropping can be caused by just about anything including mismatched negotiation, bad data being sent and/or network failures. It is a very common issue with network calls.

    Michael Taylor http://www.michaeltaylorp3.net

    Friday, November 3, 2017 2:34 PM
    Moderator