Shubham Kadam

Shubham Kadam

  • NA
  • 10
  • 7.3k

An existing connection was forcibly closed by the remot host

Nov 2 2017 7:32 AM
We are trying to develop Asynchronous socket to which multiple GPS devices will connect and Server Socket will respond to them all. But There is an exception in the program in BeginAccept Callback, which throws an exception as "An existing connection was forcibly closed by the remote host". While calling to ReceiveCallBack for particularly connected socket it throws this exception. Can you please help us?
 
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);
                     }

               }
         }
   }
} 

Answers (2)