Click here to Skip to main content
15,909,941 members
Home / Discussions / C#
   

C#

 
QuestionC# Input id Insert problems Pin
7007654323-Oct-18 21:16
7007654323-Oct-18 21:16 
QuestiondateTimePicker / smtp client Pin
User 1367511423-Oct-18 1:50
User 1367511423-Oct-18 1:50 
AnswerRe: dateTimePicker / smtp client Pin
BillWoodruff23-Oct-18 3:34
professionalBillWoodruff23-Oct-18 3:34 
GeneralRe: dateTimePicker / smtp client Pin
User 1367511424-Oct-18 1:23
User 1367511424-Oct-18 1:23 
AnswerRe: dateTimePicker / smtp client Pin
OriginalGriff23-Oct-18 4:23
mveOriginalGriff23-Oct-18 4:23 
GeneralRe: dateTimePicker / smtp client Pin
User 1367511424-Oct-18 1:21
User 1367511424-Oct-18 1:21 
GeneralRe: dateTimePicker / smtp client Pin
OriginalGriff24-Oct-18 1:35
mveOriginalGriff24-Oct-18 1:35 
QuestionC# Socket TCP - Change the client class to send the file, and the server receives the file. Pin
Member 1181344422-Oct-18 6:13
Member 1181344422-Oct-18 6:13 
I found the C# source file with the asynchronous class for sending large files via socket tcp between server and client. But my application is necessary that client send file for server.

I'm unable to change class AsynchronousClient.cs to receive file of server.
I need help adjusting the client class to send files.

Many thanks.


https://code.msdn.microsoft.com/windowsdesktop/Fixed-size-large-file-dfc3f45d


Client.cs

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;

namespace Client
{
    /// <summary>
    /// Client can connect to the server.
    /// </summary>
    public partial class Client : Form
    {
        #region Constructor

        public Client()
        {
            InitializeComponent();
        }

        #endregion

        #region Button Event

        /// <summary>
        /// Connect the server with the given ip address and port.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConnect_Click(object sender, EventArgs e)
        {
            int port;
            IPAddress ipAddress;

            if (string.IsNullOrEmpty(tbxAddress.Text) || string.IsNullOrEmpty(tbxPort.Text))
            {
                MessageBox.Show(this,Properties.Resources.IsEmptyMsg);
                return;
            }

            try
            {
                ipAddress = IPAddress.Parse(tbxAddress.Text);
            }
            catch
            {
                MessageBox.Show(this,Properties.Resources.InvalidAddressMsg);
                return;
            }

            try
            {
                port = Convert.ToInt32(tbxPort.Text);
            }
            catch
            {
                MessageBox.Show(this,Properties.Resources.InvalidPortMsg);
                return;
            }

            if (port < 0 || port > 65535)
            {
                MessageBox.Show(this, Properties.Resources.InvalidPortMsg);
                return;
            }

            if (string.IsNullOrEmpty(tbxSavePath.Text))
            {
                MessageBox.Show(this, Properties.Resources.EmptyPath);
                return;
            }

            AsynchronousClient.IpAddress = ipAddress;
            AsynchronousClient.Port = port;
            AsynchronousClient.FileSavePath = tbxSavePath.Text;
            AsynchronousClient.Client = this;

            Thread threadClient= new Thread(new ThreadStart(AsynchronousClient.StartClient));
            threadClient.IsBackground = true;
            threadClient.Start();
            btnConnect.Enabled = false;
        }

        /// <summary>
        /// Set the path to store the file sent from the server.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSavePath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog path = new FolderBrowserDialog();
            path.ShowDialog();
            this.tbxSavePath.Text = path.SelectedPath;
        }

        #endregion

        #region Change the progressBar

        /// <summary>
        /// Set the progress length of the progressBar
        /// </summary>
        /// <param name="len"></param>
        public void SetProgressLength(int len)
        {
            progressBar.Minimum = 0;
            progressBar.Maximum = len;
            progressBar.Value = 0;
            progressBar.Step = 1;
        }

        /// <summary>
        /// Change the position of the progressBar
        /// </summary>
        public void ProgressChanged()
        {
            progressBar.PerformStep();
        }

        #endregion

        #region Functions

        /// <summary>
        /// Notify the user when receive the file completely.
        /// </summary>
        public void FileReceiveDone()
        {
            MessageBox.Show(this, Properties.Resources.FileReceivedDoneMsg);
        }

        /// <summary>
        /// Notify the user when connect to the server successfully.
        /// </summary>
        public void ConnectDone()
        {
            MessageBox.Show(this,Properties.Resources.ConnectionMsg);
        }

        /// <summary>
        /// Enable the Connect button if failed to connect the sever. 
        /// </summary>
        public void EnableConnectButton()
        {
            btnConnect.Enabled = true;
        }

        #endregion

    }
}


AsynchonousClient.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Client
{
    /// <summary>
    /// AsynchronousClient is used to asynchronously receive the file from server.
    /// </summary>
    public static class AsynchronousClient
    {
        #region Members

        private static string fileName;
        private static string fileSavePath = "C:/";
        private static long fileLen;

        private static AutoResetEvent connectDone = new AutoResetEvent(false);
        private static ManualResetEvent receiveDone = new ManualResetEvent(false);
        private static bool connected = false;

        private delegate void ProgressChangeHandler();
        private delegate void FileReceiveDoneHandler();
        private delegate void ConnectDoneHandler();
        private delegate void EnableConnectButtonHandler();
        private delegate void SetProgressLengthHandler(int len);

        #endregion

        public static IDictionary<Socket, IPEndPoint> ClientsToSend = new Dictionary<Socket, IPEndPoint>();
        public static string FileToSend { get; set; }
        private const int c_bufferSize = 5242880;
        private static int signal;
        private static ManualResetEvent allDone = new ManualResetEvent(false);
        private static ManualResetEvent sendDone = new ManualResetEvent(false);
        private delegate void RemoveItemHandler(string ipAddress);
        private delegate void CompleteSendHandler();
        public static IList<Socket> Clients = new List<Socket>();

        #region Properties

        public static Client Client { get; set; }
        public static IPAddress IpAddress { get; set; }
        public static int Port { get; set; }
        public static string FileSavePath
        {
            get
            {
                return fileSavePath;
            }
            set
            {
                fileSavePath = value.Replace("\\", "/");
            }
        }

        #endregion

        #region Functions 

        /// <summary>
        /// Start connect to the server.
        /// </summary>
        public static void StartClient()
        {
            connected = false;
            if (IpAddress == null)
            {
                MessageBox.Show(Properties.Resources.InvalidAddressMsg);
                return;
            }

            IPEndPoint remoteEP = new IPEndPoint(IpAddress, Port);

            // Use IPv4 as the network protocol,if you want to support IPV6 protocol, you can update here.
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // Begin to connect the server.
            clientSocket.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), clientSocket);
            connectDone.WaitOne();

            if (connected)
            {
                // Begin to receive the file after connecting to server successfully.
                Receive(clientSocket);
                receiveDone.WaitOne();

                // Notify the user whether receive the file completely.
                Client.BeginInvoke(new FileReceiveDoneHandler(Client.FileReceiveDone));

                // Close the socket.
                clientSocket.Shutdown(SocketShutdown.Both);
                clientSocket.Close();
            }
            else
            {
                Thread.CurrentThread.Abort();
            }
        }

        /// <summary>
        /// Callback when the client connect to the server successfully.
        /// </summary>
        /// <param name="ar"></param>
        private static void ConnectCallback(IAsyncResult ar)
        {
            try
            {
                Socket clientSocket = (Socket)ar.AsyncState;

                clientSocket.EndConnect(ar);
            }
            catch
            {
                MessageBox.Show(Properties.Resources.InvalidConnectionMsg);
                Client.BeginInvoke(new EnableConnectButtonHandler(Client.EnableConnectButton));
                connectDone.Set();
                return;
            }

            Client.BeginInvoke(new ConnectDoneHandler(Client.ConnectDone));
            connected = true;
            connectDone.Set();
        }

        /// <summary>
        /// Receive the file information send by the server.
        /// </summary>
        /// <param name="clientSocket"></param>
        private static void ReceiveFileInfo(Socket clientSocket)
        {
            // Get the filename length from the server.
            byte[] fileNameLenByte = new byte[4];
            try
            {
                clientSocket.Receive(fileNameLenByte);
            }
            catch
            {
                if (!clientSocket.Connected)
                {
                    HandleDisconnectException();
                }
            }
            int fileNameLen = BitConverter.ToInt32(fileNameLenByte, 0);

            // Get the filename from the server.
            byte[] fileNameByte = new byte[fileNameLen];

            try
            {
                clientSocket.Receive(fileNameByte);
            }
            catch
            {
                if (!clientSocket.Connected)
                {
                    HandleDisconnectException();
                }
            }

            fileName = Encoding.ASCII.GetString(fileNameByte, 0, fileNameLen);

            fileSavePath = fileSavePath + "/" + fileName;

            // Get the file length from the server.
            byte[] fileLenByte = new byte[8];
            clientSocket.Receive(fileLenByte);
            fileLen = BitConverter.ToInt64(fileLenByte, 0);
        }

        /// <summary>
        /// Receive the file send by the server.
        /// </summary>
        /// <param name="clientSocket"></param>
        private static void Receive(Socket clientSocket)
        {
            StateObject state = new StateObject();
            state.WorkSocket = clientSocket;

            ReceiveFileInfo(clientSocket);

            int progressLen = checked((int)(fileLen / StateObject.BufferSize + 1));
            object[] length = new object[1];
            length[0] = progressLen;
            Client.BeginInvoke(new SetProgressLengthHandler(Client.SetProgressLength), length);

            // Begin to receive the file from the server.
            try
            {
                clientSocket.BeginReceive(state.Buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
            }
            catch
            {
                if (!clientSocket.Connected)
                {
                    HandleDisconnectException();
                }
            }
        }

        /// <summary>
        /// Callback when receive a file chunk from the server successfully.
        /// </summary>
        /// <param name="ar"></param>
        private static void ReceiveCallback(IAsyncResult ar)
        {
            StateObject state = (StateObject)ar.AsyncState;
            Socket clientSocket = state.WorkSocket;
            BinaryWriter writer;

            int bytesRead = clientSocket.EndReceive(ar);
            if (bytesRead > 0)
            {
                //If the file doesn't exist, create a file with the filename got from server. If the file exists, append to the file.
                if (!File.Exists(fileSavePath))
                {
                    writer = new BinaryWriter(File.Open(fileSavePath, FileMode.Create));
                }
                else
                {
                    writer = new BinaryWriter(File.Open(fileSavePath, FileMode.Append));
                }

                writer.Write(state.Buffer, 0, bytesRead);
                writer.Flush();
                writer.Close();

                // Notify the progressBar to change the position.
                Client.BeginInvoke(new ProgressChangeHandler(Client.ProgressChanged));

                // Recursively receive the rest file.
                try
                {
                    clientSocket.BeginReceive(state.Buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
                }
                catch
                {
                    if (!clientSocket.Connected)
                    {
                        MessageBox.Show(Properties.Resources.DisconnectMsg);
                    }
                }
            }
            else
            {
                // Signal if all the file received.
                receiveDone.Set();
            }
        }

        #endregion

        #region Private Functions

        /// <summary>
        /// Handle the exception when disconnect from the server.
        /// </summary>
        private static void HandleDisconnectException()
        {
            MessageBox.Show(Properties.Resources.DisconnectMsg);
            Client.BeginInvoke(new EnableConnectButtonHandler(Client.EnableConnectButton));
            Thread.CurrentThread.Abort();
        }

        #endregion

    }
}


Program.cs


using System;
using System.Threading;
using System.Windows.Forms;

namespace Client
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
            Application.Run(new Client());
        }

        public static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            MessageBox.Show(e.Exception.Message);
        }
    }
}



Server


Server.cs

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;

namespace Server
{
    /// <summary>
    /// The server used to listen the client connection and send file to them. 
    /// </summary>
    public partial class Server : Form
    {
        private static bool HasStartup = false;

        #region Constructor

        public Server()
        {
            InitializeComponent();
        }

        #endregion

        #region Button Event

        private void btnStartup_Click(object sender, EventArgs e)
        {
            if (!HasStartup)
            {
                try
                {
                    AsynchronousSocketListener.Port = tbxPort.Text;
                }
                catch(Exception ex)
                {
                    MessageBox.Show(this,ex.Message);
                    return;
                }
                AsynchronousSocketListener.Server = this;
                Thread listener = new Thread(new ThreadStart(AsynchronousSocketListener.StartListening));
                listener.IsBackground = true;
                listener.Start();
                HasStartup = true;
            }

            MessageBox.Show(this,Properties.Resources.StartupMsg);
        }

        private void btnSelectFile_Click(object sender, EventArgs e)
        {
            openFileDialog.Multiselect = false;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                tbxFile.Text = openFileDialog.FileName;
                AsynchronousSocketListener.FileToSend = tbxFile.Text;
            }
            
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            if(lbxServer.SelectedItems.Count == 0)
            {
                MessageBox.Show(this,Properties.Resources.SelectClientMsg);
                return;
            }

            if (string.IsNullOrEmpty(tbxFile.Text))
            {
                MessageBox.Show(this,Properties.Resources.EmptyFilePathMsg);
                return;
            }

            if(AsynchronousSocketListener.Clients.Count == 0)
            {
                MessageBox.Show(this,Properties.Resources.ConnectionMsg);
                return;
            }

            foreach (object item in lbxServer.SelectedItems)
            {
                foreach (Socket handler in AsynchronousSocketListener.Clients)
                {
                    IPEndPoint ipEndPoint = (IPEndPoint)handler.RemoteEndPoint;
                    string address = ipEndPoint.ToString();
                    if (string.Equals(item.ToString(), address, StringComparison.OrdinalIgnoreCase))
                    {
                        AsynchronousSocketListener.ClientsToSend.Add(handler,ipEndPoint);
                        break;
                    }
                }
            }

            Thread sendThread = new Thread(new ThreadStart(AsynchronousSocketListener.Send));
            sendThread.IsBackground = true;
            sendThread.Start();
            btnSend.Enabled = false;

        }

        #endregion

        #region ListBox item change functions

        /// <summary>
        /// Add the client address to lbxClient.
        /// </summary>
        /// <param name="IpEndPoint"></param>
        public void AddClient(IPEndPoint IpEndPoint)
        {
            lbxServer.BeginUpdate();
            lbxServer.Items.Add(IpEndPoint.ToString());
            lbxServer.EndUpdate();
        }

        /// <summary>
        /// Clear the content of lbxClient.
        /// </summary>
        public void CompleteSend()
        {
            while (lbxServer.SelectedIndices.Count > 0)
            {
                lbxServer.Items.RemoveAt(lbxServer.SelectedIndices[0]);
            }
            btnSend.Enabled = true;
        }

        /// <summary>
        /// Remove the client address which disconnect from the server.
        /// </summary>
        /// <param name="ipAddress"></param>
        public void RemoveItem(string ipAddress)
        {
            int index = 0;
            bool flag = false;

            foreach (object item in lbxServer.SelectedItems)
            {
                if (!string.Equals(item.ToString(), ipAddress, StringComparison.OrdinalIgnoreCase))
                {
                    index++;
                }
                else
                {
                    flag = true;
                    break;
                }
            }

            if (flag)
            {
                lbxServer.Items.RemoveAt(index);
            }
        }

        /// <summary>
        /// Enable the Send button.
        /// </summary>
        public void EnableSendButton()
        {
            btnSend.Enabled = true;
        }

        #endregion
    }
}


AsynchronousSocketListener.cs

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace Server
{
    /// <summary>
    /// AsynchronousSocketListener is used to asynchronously listen the client and send file to the client.
    /// </summary>
    public static class AsynchronousSocketListener
    {
        #region Constants

        private const int c_clientSockets = 100;
        private const int c_bufferSize = 5242880;

        #endregion

        #region Memebers

        private static int port;
        private static int signal;
        private static ManualResetEvent allDone = new ManualResetEvent(false);
        private static ManualResetEvent sendDone = new ManualResetEvent(false);
        private delegate void AddClientHandler(IPEndPoint IpEndPoint);
        private delegate void CompleteSendHandler();
        private delegate void RemoveItemHandler(string ipAddress);
        private delegate void EnableSendHandler();

        #endregion

        #region Properties

        public static Server Server { get; set; }
        public static string Port 
        {
            set
            {
                try
                {
                    port = Convert.ToInt32(value);
                }
                catch (FormatException)
                {
                    throw new Exception(Properties.Resources.InvalidPortMsg);
                }
                catch (OverflowException ex)
                {
                    throw new Exception(ex.Message);
                }

                if (port < 0 || port > 65535)
                {
                    throw new Exception(Properties.Resources.InvalidPortMsg);
                }
            }
        }
        public static string FileToSend { get; set; }
        public static IList<Socket> Clients = new List<Socket>();
        public static IDictionary<Socket,IPEndPoint> ClientsToSend = new Dictionary<Socket,IPEndPoint>();

        #endregion 

        #region Functions

        /// <summary>
        /// Server start to listen the client connection.
        /// </summary>
        public static void StartListening()
        {
            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, port);

            // Use IPv4 as the network protocol,if you want to support IPV6 protocol, you can update here.
            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                listener.Bind(localEndPoint);
            }
            catch (SocketException ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            listener.Listen(c_clientSockets);

            //loop listening the client.
            while (true)
            {
                allDone.Reset();
                listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
                allDone.WaitOne();
            }
        }

        /// <summary>
        /// Callback when one client successfully connected to the server.
        /// </summary>
        /// <param name="ar"></param>
        private static void AcceptCallback(IAsyncResult ar)
        {
            Socket listener = (Socket)ar.AsyncState;
            Socket handler = listener.EndAccept(ar);

            IPEndPoint ipEndPoint = handler.RemoteEndPoint as IPEndPoint;

            if ((ipEndPoint) != null)
            {
                Server.BeginInvoke(new AddClientHandler(Server.AddClient),ipEndPoint);
            }

            Clients.Add(handler);
            
            allDone.Set();
        }

        /// <summary>
        /// Send file information to clients.
        /// </summary>
        public static void SendFileInfo()
        {
            string fileName = FileToSend.Replace("\\", "/");
            IList<Socket> closedSockets = new List<Socket>();
            IList<String> removedItems = new List<String>();

            while (fileName.IndexOf("/") > -1)
            {
                fileName = fileName.Substring(fileName.IndexOf("/") + 1);
            }

            FileInfo fileInfo = new FileInfo(FileToSend);
            long fileLen = fileInfo.Length;

            byte[] fileLenByte = BitConverter.GetBytes(fileLen);

            byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName);

            byte[] clientData = new byte[4 + fileNameByte.Length + 8];

            byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);

            fileNameLen.CopyTo(clientData, 0);
            fileNameByte.CopyTo(clientData, 4);
            fileLenByte.CopyTo(clientData, 4 + fileNameByte.Length);

            // Send the file name and length to the clients. 
            foreach (KeyValuePair<Socket, IPEndPoint> kvp in ClientsToSend)
            {
                Socket handler = kvp.Key;
                IPEndPoint ipEndPoint = kvp.Value;
                try
                {
                    handler.Send(clientData);
                }
                catch
                {
                    if (!handler.Connected)
                    {
                        closedSockets.Add(handler);

                        removedItems.Add(ipEndPoint.ToString());
                    }
                }
            }

            // Remove the clients which are disconnected.
            RemoveClient(closedSockets);
            RemoveClientItem(removedItems);
            closedSockets.Clear();
            removedItems.Clear();
        }

        /// <summary>
        /// Send file from server to clients.
        /// </summary>
        public static void Send()
        {
            int readBytes = 0;
            byte[] buffer = new byte[c_bufferSize];
            IList<Socket> closedSockets = new List<Socket>();
            IList<String> removedItems = new List<String>();

            // Send file information to the clients.
            SendFileInfo();

            // Blocking read file and send to the clients asynchronously.
            using (FileStream stream = new FileStream(FileToSend, FileMode.Open))
            {
                do
                {
                    sendDone.Reset();
                    signal = 0;
                    stream.Flush();
                    readBytes = stream.Read(buffer,0,c_bufferSize);

                    if (ClientsToSend.Count == 0)
                    {
                        sendDone.Set();
                    }

                    foreach (KeyValuePair<Socket,IPEndPoint> kvp in ClientsToSend)
                    {
                        Socket handler = kvp.Key;
                        IPEndPoint ipEndPoint = kvp.Value;
                        try
                        {
                            handler.BeginSend(buffer, 0, readBytes, SocketFlags.None, new AsyncCallback(SendCallback), handler);
                        }
                        catch
                        {
                            if (!handler.Connected)
                            {
                                closedSockets.Add(handler);
                                signal++;
                                removedItems.Add(ipEndPoint.ToString());

                                // Signal if all the clients are disconnected.
                                if (signal >= ClientsToSend.Count)
                                {
                                    sendDone.Set();
                                }
                            }
                        }
                    }
                    sendDone.WaitOne();

                    // Remove the clients which are disconnected.
                    RemoveClient(closedSockets);
                    RemoveClientItem(removedItems);
                    closedSockets.Clear();
                    removedItems.Clear();
                }
                while (readBytes > 0);
            }

            // Disconnect all the connection when the file has send to the clients completely.
            ClientDisconnect();
            CompleteSendFile();
        }

        /// <summary>
        /// Callback when a part of the file has been sent to the clients successfully.
        /// </summary>
        /// <param name="ar"></param>
        private static void SendCallback(IAsyncResult ar)
        {
            lock (Server)
            {
                Socket handler = null;
                try
                {
                    handler = (Socket)ar.AsyncState;
                    signal++;
                    int bytesSent = handler.EndSend(ar);

                    // Close the socket when all the data has sent to the client.
                    if (bytesSent == 0)
                    {
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                    }
                }
                catch (ArgumentException argEx)
                {
                    MessageBox.Show(argEx.Message);
                }
                catch (SocketException)
                {
                    // Close the socket if the client disconnected.
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }
                finally
                {
                    // Signal when the file chunk has sent to all the clients successfully. 
                    if (signal >= ClientsToSend.Count)
                    {
                        sendDone.Set();
                    }
                }
            }
        }

        /// <summary>
        /// Disconnect all the connection.
        /// </summary>
        private static void ClientDisconnect()
        {
            Clients.Clear();
            ClientsToSend.Clear();
        }

        /// <summary>
        /// Change the presentation of listbox when the file send to the clients finished.
        /// </summary>
        private static void CompleteSendFile()
        {
            Server.BeginInvoke(new CompleteSendHandler(Server.CompleteSend));
        }

        /// <summary>
        /// Change the presentation of listbox when the some clients disconnect the connection.
        /// </summary>
        /// <param name="ipAddressList"></param>
        private static void RemoveClientItem(IList<String> ipAddressList)
        {
            foreach (string ipAddress in ipAddressList)
            {
                Server.BeginInvoke(new RemoveItemHandler(Server.RemoveItem), ipAddress);
            }

            if (ClientsToSend.Count == 0)
            {
                Server.BeginInvoke(new EnableSendHandler(Server.EnableSendButton));
            }
        }

        /// <summary>
        /// Remove the sockets if some client disconnect the connection.
        /// </summary>
        /// <param name="listSocket"></param>
        private static void RemoveClient(IList<Socket> listSocket)
        {
            if (listSocket.Count > 0)
            {
                foreach (Socket socket in listSocket)
                {
                    Clients.Remove(socket);
                    ClientsToSend.Remove(socket);
                }
            }
        }

        #endregion
    }
}


Program.cs


using System;
using System.Windows.Forms;

namespace Server
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Server());
        }
    }
}


modified 22-Oct-18 12:53pm.

AnswerRe: C# Socket TCP - Change the client class to send the file, and the server receives the file. Pin
Afzaal Ahmad Zeeshan22-Oct-18 7:43
professionalAfzaal Ahmad Zeeshan22-Oct-18 7:43 
AnswerRe: C# Socket TCP - Change the client class to send the file, and the server receives the file. Pin
Richard MacCutchan22-Oct-18 21:37
mveRichard MacCutchan22-Oct-18 21:37 
QuestionCheque printing in winforms application using C# dotnet Pin
ccrenil20-Oct-18 1:43
ccrenil20-Oct-18 1:43 
AnswerRe: Cheque printing in winforms application using C# dotnet Pin
Afzaal Ahmad Zeeshan20-Oct-18 3:21
professionalAfzaal Ahmad Zeeshan20-Oct-18 3:21 
QuestionVery slow code in bar code reading Pin
Ali Alshihry19-Oct-18 14:57
Ali Alshihry19-Oct-18 14:57 
AnswerRe: Very slow code in bar code reading Pin
Dave Kreskowiak19-Oct-18 15:33
mveDave Kreskowiak19-Oct-18 15:33 
GeneralRe: Very slow code in bar code reading Pin
Ali Alshihry19-Oct-18 15:44
Ali Alshihry19-Oct-18 15:44 
GeneralRe: Very slow code in bar code reading Pin
Dave Kreskowiak19-Oct-18 15:58
mveDave Kreskowiak19-Oct-18 15:58 
Generalc# Identity Server 3: Set different Refresh Token Expiration for a specific user Pin
Member 1402363617-Oct-18 14:23
Member 1402363617-Oct-18 14:23 
QuestionApplication service with C#. Pin
Member 1401973516-Oct-18 20:55
Member 1401973516-Oct-18 20:55 
AnswerRe: Application service with C#. Pin
OriginalGriff16-Oct-18 21:16
mveOriginalGriff16-Oct-18 21:16 
GeneralRe: Application service with C#. Pin
Member 1401973516-Oct-18 22:09
Member 1401973516-Oct-18 22:09 
GeneralRe: Application service with C#. Pin
OriginalGriff16-Oct-18 22:13
mveOriginalGriff16-Oct-18 22:13 
GeneralRe: Application service with C#. Pin
Member 1401973516-Oct-18 22:46
Member 1401973516-Oct-18 22:46 
GeneralRe: Application service with C#. Pin
OriginalGriff16-Oct-18 23:02
mveOriginalGriff16-Oct-18 23:02 
GeneralRe: Application service with C#. Pin
Pete O'Hanlon16-Oct-18 23:59
mvePete O'Hanlon16-Oct-18 23:59 
AnswerRe: Application service with C#. Pin
#realJSOP22-Oct-18 9:03
professional#realJSOP22-Oct-18 9:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.