locked
How can I resolve : System.Net.Sockets.SocketException: 'An existing connection was forcibly closed by the remote host' RRS feed

  • Question

  • User-978659149 posted

    I create a TCP connection between a server and a client, but after few requests I have this error message :

    System.Net.Sockets.SocketException: 'An existing connection was forcibly closed by the remote host'

    On this line :

    _clientSocket.Send(buffer,0,buffer.Length,SocketFlags.None);

    And when I stop my client my server stop.

    SERVER CODE :

        private static Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        private static List<Socket> _clientSockets = new List<Socket>();
        private static byte[] _buffer = new byte[2048];
        
        protected override void OnStart(string[] args)
        {
        
            SetupServer();
        
        }
    
        private static void SetupServer()
        {
            Log.writeEventLog("Setting up server...");
            _serverSocket.Bind(new IPEndPoint(IPAddress.Any, 100));
            _serverSocket.Listen(1);// max listen client
            _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
        }
    
        private static void AcceptCallback(IAsyncResult AR)
        {
            Socket socket = _serverSocket.EndAccept(AR);
            _clientSockets.Add(socket);
            Log.writeEventLog("Client connected");
            socket.BeginReceive(_buffer,0,_buffer.Length,SocketFlags.None,new AsyncCallback(ReceiveCallback),socket);
            _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
        }
    
        private static void ReceiveCallback(IAsyncResult AR)
        {
            Socket socket = (Socket)AR.AsyncState;
            int received = socket.EndReceive(AR);
            byte[] dataBuf = new byte[received];
            Array.Copy(_buffer,dataBuf,received);
    
            string text = Encoding.ASCII.GetString(dataBuf);
            Log.writeEventLog("TEXT RECEIVED: " + text);
    
            string response = string.Empty;
    
            if(text.ToLower() != "get authentication key")
            {
                response = "Invalid Request";
            }
            else
            {
                response = "TEST";
            }
    
            byte[] data = Encoding.ASCII.GetBytes(response);
            socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallBack), null);
            socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
        }
    
        private static void SendCallBack(IAsyncResult AR)
        {
            Socket socket = (Socket)AR.AsyncState;
            socket.EndSend(AR);
        }
    

    CLIENT CODE

        private static Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        static void Main(string[] args)
        {
        
            LoopConnect();
            SendLoop();
            Console.ReadLine();
            Console.ReadKey();
        
        }  
    
        private static void SendLoop()
        {
            while (true)
            {
                Console.WriteLine("Enter a request: ");
                string req = Console.ReadLine();
    
                byte[] buffer = Encoding.ASCII.GetBytes(req);
                _clientSocket.Send(buffer,0,buffer.Length,SocketFlags.None);
    
                var receivedBuffer = new byte[2048];
                int rec = _clientSocket.Receive(receivedBuffer,SocketFlags.None);
    
                byte[] data = new byte[rec];
                Array.Copy(receivedBuffer, data, rec);
                Console.WriteLine("Received : " + Encoding.ASCII.GetString(data));
            }
        }
    
        private static void LoopConnect()
        {
            int attempts = 0;
            while (!_clientSocket.Connected)
            {
                try
                {
                    attempts++;
                    _clientSocket.Connect(IPAddress.Loopback, 100);
                }
                catch (SocketException) {
                    Console.Clear();
                    Console.WriteLine("Connection attenpts: "+ attempts.ToString());
                }
            }
    
            Console.Clear();
            Console.WriteLine("Connected");
        }

    Someone have any idea how can I resolve the errors ?

    Friday, January 17, 2020 3:11 PM

Answers

  • User1535942433 posted

    Hi soleyne,

    socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallBack), null);

    Accroding to your code,I think BeginSend have more than two parameter.One is AsyncCallback, another is your variable.Since you passed in null, you can only get null.

    I suggest you could create a state object for receiving data sent by the client.

    More details,you could refer to below articles:

    https://docs.microsoft.com/en-us/dotnet/framework/network-programming/using-an-asynchronous-server-socket

    Best regards,

    Yijing Sun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, January 20, 2020 3:44 AM

All replies

  • User475983607 posted

    The error commonly indicates the server is on longer listening.  If the code works for a while then stops, there is probably an exception or the connections are not being closed and you've exhausted all the connections.  

    Friday, January 17, 2020 3:46 PM
  • User-978659149 posted

    I put try catch every where in my server code and in SendCallBack I have this error :

    Object reference not set to an instance of an object

    Friday, January 17, 2020 3:59 PM
  • User475983607 posted
    Please debug your code. Try writing the stack trace as well as any inner exception for more information on the error.
    Friday, January 17, 2020 4:27 PM
  • User1535942433 posted

    Hi soleyne,

    socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallBack), null);

    Accroding to your code,I think BeginSend have more than two parameter.One is AsyncCallback, another is your variable.Since you passed in null, you can only get null.

    I suggest you could create a state object for receiving data sent by the client.

    More details,you could refer to below articles:

    https://docs.microsoft.com/en-us/dotnet/framework/network-programming/using-an-asynchronous-server-socket

    Best regards,

    Yijing Sun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, January 20, 2020 3:44 AM
  • User-978659149 posted

    Thank you I forget to replace null by socket.

    Monday, January 20, 2020 9:20 AM