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 9215841
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T02:17:35+00:00 2026-06-18T02:17:35+00:00

I have a client-server applications. The server can handle multiple client connections. When I

  • 0

I have a client-server applications.
The server can handle multiple client connections.

When I click the Close button in the client, I expect it to be disconnected, and removed from the list of clients in the server form.

However, it enters an infinite loop, which causes the client to be removed from the form’s ListView, and then added again to the form’s ListView.

Here is my code:

RemoteBatcherClientForm:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace RemoteBatcherClient
{
    public partial class RemoteBatcherClientForm : Form
    {
        Socket clientSock;

        public RemoteBatcherClientForm()
        {
            InitializeComponent();
            clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        private void connectBtn_Click(object sender, EventArgs e)
        {
            clientSock.Connect("127.0.0.1", 8);
            MessageBox.Show("Connected");
        }

        private void sendBtn_Click(object sender, EventArgs e)
        {
            if (clientSock.Send(Encoding.Default.GetBytes(txtMsg.Text)) > 0)
            {
                MessageBox.Show("Data Sent");
            }
        }

        private void closeBtn_Click(object sender, EventArgs e)
        {
            clientSock.Close();
            clientSock.Dispose();
            Close();
        }
    }
}

RemoteBatcherServer:

Client.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace RemoteBatcherServer
{
    class Client
    {
        public string ID
        {
            get;
            private set;
        }

        public IPEndPoint EndPoint
        {
            get;
            private set;
        }

        Socket serverSock;

        public Client(Socket accepted)
        {
            serverSock = accepted;

            ID = Guid.NewGuid().ToString();
            EndPoint = (IPEndPoint)serverSock.RemoteEndPoint;
            serverSock.BeginReceive(new byte[] { 0 }, 0, 0, 0, callback, null);
        }

        void callback(IAsyncResult ar)
        {
            try
            {
                serverSock.EndReceive(ar);

                byte[] receiveBuffer = new byte[8192];

                int rec = serverSock.Receive(receiveBuffer, receiveBuffer.Length, 0);

                if (rec < receiveBuffer.Length)
                {
                    Array.Resize<byte>(ref receiveBuffer, rec);
                }

                 if (Receieved != null)
                {
                    Receieved(this, receiveBuffer);
                }

                serverSock.BeginReceive(new byte [] {0}, 0, 0, 0, callback, null);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
                Close();

                if (Disconnected != null)
                {
                    Disconnected(this);
                }
            }
        }

        public void Close()
        {
            serverSock.Close();
            serverSock.Dispose();
        }

        public delegate void ClientReceievedHandler(Client sender, byte[] data);
        public delegate void ClientDisconnectedHandler(Client sender);

        public event ClientReceievedHandler Receieved;
        public event ClientDisconnectedHandler Disconnected;
    }
}

Listener.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace RemoteBatcherServer
{
    class Listener
    {
        Socket sck;

        public bool Listening
        {
            get;
            private set;
        }

        public int Port
        {
            get;
            private set;
        }

        public Listener(int port)
        {
            Port = port;
            sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        public void Start()
        {
            if (Listening)
                return;

            sck.Bind(new IPEndPoint(0, Port));
            sck.Listen(0);

            sck.BeginAccept(callback, null);

            Listening = true;
        }

        public void Stop()
        {
            if (!Listening)
                return;

            sck.Close();
            sck.Dispose();
            sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        void callback(IAsyncResult ar)
        {
            try
            {
                Socket acceptSocket = sck.EndAccept(ar);

                if (SockeetAccepted != null)
                {
                    SockeetAccepted(acceptSocket);
                }

                sck.BeginAccept(callback, null);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        public delegate void SocketAcceptHandler(Socket acceptSocket);
        public event SocketAcceptHandler SockeetAccepted;
    }
}

RemoteBatcherServerForm.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace RemoteBatcherServer
{
    public partial class RemoteBatcherServerForm : Form
    {
        Listener listener;

        public RemoteBatcherServerForm()
        {
            InitializeComponent();
            listener = new Listener(8);
            listener.SockeetAccepted += new Listener.SocketAcceptHandler(listenerSocketAccepted);

            Load += new EventHandler(MainLoad);
        }

        void MainLoad(object sender, EventArgs e)
        {
            listener.Start();
        }

        void listenerSocketAccepted(Socket socket)
        {
            Client client = new Client(socket);
            client.Receieved += new Client.ClientReceievedHandler(clientReceived);
            client.Disconnected += new Client.ClientDisconnectedHandler(clientDisconnected);

            Invoke((MethodInvoker)delegate
            {
                ListViewItem item = new ListViewItem();
                item.Text = client.EndPoint.ToString();
                item.SubItems.Add(client.ID);
                item.SubItems.Add("XX");
                item.SubItems.Add("XX");
                item.Tag = client;
                lstClients.Items.Add(item);
            });
        }

        void clientReceived(Client sender, byte[] data)
        {
            Invoke((MethodInvoker)delegate
            {
                for (int i = 0; i < lstClients.Items.Count; i++)
                {
                    Client client = lstClients.Items[i].Tag as Client;

                    if (client.ID == sender.ID)
                    {
                        lstClients.Items[i].SubItems[2].Text = Encoding.Default.GetString(data);
                        lstClients.Items[i].SubItems[3].Text = DateTime.Now.ToString();
                        break;
                    }
                }
            });
        }

        void clientDisconnected(Client sender)
        {
            Invoke((MethodInvoker)delegate
            {
                for (int i = 0; i < lstClients.Items.Count; i++)
                {
                    Client client = lstClients.Items[i].Tag as Client;

                    if (client.ID == sender.ID)
                    {
                        lstClients.Items.RemoveAt(i);
                        break;
                    }
                }
            });
        }       
    }
}

Any ideas?

  • 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-18T02:17:36+00:00Added an answer on June 18, 2026 at 2:17 am

    Here’s a quick answer: modify the Client.cs‘s void callback(IAsyncResult ar) method in order to check if the Socket.Available Property returns 0 (this happens when the client is closed):

    void callback(IAsyncResult ar)
    {
        try
        {
            //add these lines
            if (serverSock.Available == 0)
            {
                Disconnected(this);
                return;
            }
    
            serverSock.EndReceive(ar);
    
            byte[] receiveBuffer = new byte[8192];
    
            int rec = serverSock.Receive(receiveBuffer, receiveBuffer.Length, 0);
    
            if (rec < receiveBuffer.Length)
            {
                Array.Resize<byte>(ref receiveBuffer, rec);
            }
    
            if (Receieved != null)
            {
                Receieved(this, receiveBuffer);
            }
    
            serverSock.BeginReceive(new byte[] { 0 }, 0, 0, 0, callback, null);
        }
        catch (System.Exception ex)
        {
            Console.WriteLine(ex.Message);
            Close();
    
            if (Disconnected != null)
            {
                Disconnected(this);
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a server application receiving messages from a JMS queue. And client applications
I have written a TCP server application in C code that can handle multiple
I have client/server applications and a very simple protocol for communication. More precisely, it's
I currently have a Firebird server on Windows and Windows desktop client applications for
I have a client-server application using envisage framework, I'm using threads to handle the
I have client/server application where the client app will open files. Those files get
I have a client/server application where data is exchanged in XML format. The size
I have some client-server application. And as one of its part, I need to
I have a Client/Server application, where the Client and Server have some common tables
I have a client server application in which the server and the client need

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.