Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9115343
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T04:24:31+00:00 2026-06-17T04:24:31+00:00

I have written a server side code using Sockets, Its working fine but have

  • 0

I have written a server side code using Sockets, Its working fine but have one problem I don’t know how to handle this scenario: if client just closes application without sending Disconnect request, my server side program crashes. What do I need to do to avoid this? Please guide me I am new to Socket programming.

private void OnReceive(IAsyncResult result)
{
    try
    {
        Socket clientSocket = (Socket)result.AsyncState;
        clientSocket.EndReceive(result);

        command = responseMessage = string.Empty;
        command = ByteToString(receviedData);
        receviedData = new byte[30];

        if (command=="Connect")
        {
            ClientInfo clientInfo = new ClientInfo();
            clientInfo.socket = clientSocket;
            clientInfo.IP = clientSocket.RemoteEndPoint.ToString();
            connectedClients.Add(clientInfo);
            responseMessage = "Connection established...";
        }
        else if (command=="Disconnect")
        {
            for (int i = 0; i < connectedClients.Count; i++)
            {
                if (connectedClients[i].socket == clientSocket)
                {
                    connectedClients.RemoveAt(i);
                    break;
                }
            }
            clientSocket.Close();
        }
        else
        {
            responseMessage = "Error";
        }

        byte[] responseStatus = StringToByte(responseMessage);
        for (int i = 0; i < connectedClients.Count; i++)
        {
            if (connectedClients[i].socket==clientSocket)
            {
                connectedClients[i].socket.BeginSend(responseStatus, 0, responseStatus.Length,SocketFlags.None, new AsyncCallback(OnSend), connectedClients[i].socket);
                break;
            }
        }

    }
    catch(Exception ex)
    {
      throw new Exception(ex.Message);
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T04:24:32+00:00Added an answer on June 17, 2026 at 4:24 am

    Your application crashes, because you throw an exception in the catch block of your method.

    If you don’t want your application to crash, you need to remove the throw new Exception(ex.Message); line from the catch block.
    Replace it with code that handles the error and gracefully restores your application to a safe state. From reading your code, this should be done by removing the clientSocket from connectedClients

    Secondly, it is better to just use throw; instead of throw new Exception(ex.Message);. throw; will re-throw the original exception object and thus preserve the stack trace and other vital information that helps in debugging your software.
    Using new Exception("Message") will create a completely new exception object with the current stack trace.

    private void OnReceive(IAsyncResult result)
    {
        try
        {
            Socket clientSocket = (Socket)result.AsyncState;
            clientSocket.EndReceive(result);
    
            command = responseMessage = string.Empty;
            command = ByteToString(receviedData);
            receviedData = new byte[30];
    
            if (command=="Connect")
            {
                ClientInfo clientInfo = new ClientInfo() {
                   socket = clientSocket,
                   IP = clientSocket.RemoteEndPoint.ToString(),
                   }; 
                connectedClients.Add(clientInfo);
                responseMessage = "Connection established...";
            }
            else if (command=="Disconnect")
            {
                removeClientInfo(clientSocket);
                clientSocket.Close();
            }
            else
            {
                responseMessage = "Error";
            }
    
            byte[] responseStatus = StringToByte(responseMessage);
            for (int i = 0; i < connectedClients.Count; i++)
            {
                if (connectedClients[i].socket==clientSocket)
                {
                    connectedClients[i].socket.BeginSend(responseStatus, 0, responseStatus.Length,SocketFlags.None, new AsyncCallback(OnSend), connectedClients[i].socket);
                    break;
                }
            }
    
        }
        catch(Exception ex)
        {
          // add error handling and gracefully recover
          // caution: The way done here, might work, but it smells :-/
          removeClientInfo((Socket)result.AsyncState);
          ((Socket)result.AsyncState).Close();
        }
    }
    
    /// removes the client info from the connectedClients enumerable
    private void removeClientInfo(Socket socket)
    {
        for (int i = 0; i < connectedClients.Count; i++)
        {
            if (connectedClients[i].socket == socket)
            {
                connectedClients.RemoveAt(i);
                break;
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have written the following code in the server side for a chat client
I have written a custom server control which (pseudo-code) looks like public class MyCustomCtrl
I have written a Python TCP/IP server for internal use, using win32serviceutil/py2exe to create
I have two related apps I am developing in Scala. One is a server-side
I've got some (badly written) legacy code that I have to modify but I'm
I have written a server daemon (Linux, Ubuntu) which communicates with PHP as frontend
I am trying out GWT in this 'configuration': 1) I have written a server
I have written a SQL Server stored procedure that includes a DateTime parameter. This
I have written a mini web-server which needs to serve up a few static
I have written php program and uploaded on server. I want run this program

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.