简体   繁体   中英

Display Multiple clients Name at Server side using Socket Connection in WinForms C#

In Windows-Form Application C# , I have done multiple client connection to a single server using socket connection and I can send numbers from multiple clients to single server. But the problem is that, at the server I am not able to differentiate which client is sending which number, so I need to display Client_1 , Client_2 , Client_3 and so on differently at the server side application. Please let me know how it would be better?

SERVER( at the OnDataReceived() Method how it can be changed?)

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

namespace Socket_Server
{
    public partial class Form1 : Form
    {

        const int MAX_CLIENTS = 30;

        public AsyncCallback pfnWorkerCallBack;
        private Socket m_mainSocket;
        private Socket[] m_workerSocket = new Socket[30];
        private int m_clientCount = 0;


        public StreamWriter STW;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string PortNumber = "1755";
            try
            {

                string portStr = PortNumber;
                int port = System.Convert.ToInt32(portStr);
                m_mainSocket = new Socket(AddressFamily.InterNetwork,
                                           SocketType.Stream,
                                           ProtocolType.Tcp);
                IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);
                m_mainSocket.Bind(ipLocal);
                m_mainSocket.Listen(4);

                m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);

                this.BackgroundWorker = new Thread(new ThreadStart(Startinfiniteloop));

                this.BackgroundWorker.Start();



            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }

        }

        public void Startinfiniteloop()
        {

            for (int initial_value = 0; ; initial_value++)
            {


                try
                {


                    Dictionary<string, int> d2 = new Dictionary<string, int>();

                    d2["c2"] = initial_value;




                    this.BeginInvoke((MethodInvoker)(() => Storing_Number.Items.Clear()));
                    this.BeginInvoke((MethodInvoker)(() => Storing_Number.Items.Add(d2["c2"])));

                    //Delay  Thread             
                    Thread.Sleep(1000);

                    NumberSend(  d2["c2"] + "\n");
                    this.BeginInvoke((MethodInvoker)(() => Sending_Box.Items.Add("Sending_To_CLIENT:     " + d2["c2"] + "\n")));
                    this.BeginInvoke((MethodInvoker)(() => Sending_Box.TopIndex = Sending_Box.Items.Count - 1));

                   //  this.BackgroundWorker = new Thread(new ThreadStart(NumberSend));

              //  this.BackgroundWorker.Start();


                           // STW = new StreamWriter(Sending_Box.Items[initial_value].ToString());
                          //  STW.WriteLine(Sending_Box.Items[initial_value]);
                           // STW.AutoFlush = true;

                }
                catch (Exception x)
                {

                }
            }


        }


        public void NumberSend(string mesg)
        {

            try
            {


                Object objData = mesg;

                byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());

                for (int i = 0; i < m_clientCount; i++)
                {

                    if (m_workerSocket[i] != null)
                    {
                        if (m_workerSocket[i].Connected)
                        {
                            m_workerSocket[i].Send(byData);

                        }
                    }
                }

            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }

        }


        public void OnClientConnect(IAsyncResult asyn)
        {
            try
            {
                m_workerSocket[m_clientCount] = m_mainSocket.EndAccept(asyn);


                WaitForData(m_workerSocket[m_clientCount]);
                ++m_clientCount;




                String str = String.Format("Client # {0} connected", m_clientCount);

                Invoke(new Action(() => textBoxMsg.Clear()));
                Invoke(new Action(() => textBoxMsg.AppendText(str)));
                m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }

        }

        public class SocketPacket
        {
            public System.Net.Sockets.Socket m_currentSocket;
            public byte[] dataBuffer = new byte[1024];
        }


        public void WaitForData(System.Net.Sockets.Socket soc)
        {
            try
            {
                if (pfnWorkerCallBack == null)
                {
                    pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
                }
                SocketPacket theSocPkt = new SocketPacket();
                theSocPkt.m_currentSocket = soc;// could be this one!!!
                soc.BeginReceive(theSocPkt.dataBuffer, 0,
                                   theSocPkt.dataBuffer.Length,
                                   SocketFlags.None,
                                   pfnWorkerCallBack,
                                   theSocPkt);
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }

        }

        public void OnDataReceived(IAsyncResult asyn)
        {
            try
            {
                SocketPacket socketData = (SocketPacket)asyn.AsyncState;
                int iRx = 0;
                iRx = socketData.m_currentSocket.EndReceive(asyn);
                char[] chars = new char[iRx + 1];
                System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
                int charLen = d.GetChars(socketData.dataBuffer,
                                         0, iRx, chars, 0);
                System.String szData = new System.String(chars);
                Invoke(new Action(() => richTextBoxSendMsg.AppendText(szData)));
                Invoke(new Action(() => richTextBoxSendMsg.AppendText(Environment.NewLine)));
                WaitForData(socketData.m_currentSocket);
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            CloseSockets();

            Close();
        }

        String GetIP()
        {
            String strHostName = Dns.GetHostName();
            IPHostEntry iphostentry = Dns.GetHostEntry(strHostName);

            String IPStr = "";

            foreach (IPAddress ipaddress in iphostentry.AddressList)
            {
                if (ipaddress.IsIPv6LinkLocal == false)
                {
                    IPStr = IPStr + ipaddress.ToString();
                    return IPStr;
                }

            }
            return IPStr;
        }


        void CloseSockets()
        {
            if (m_mainSocket != null)
            {
                m_mainSocket.Close();
            }
            for (int i = 0; i < m_clientCount; i++)
            {
                if (m_workerSocket[i] != null)
                {
                    m_workerSocket[i].Close();
                    m_workerSocket[i] = null;
                }
            }
        }





        public Thread BackgroundWorker { get; set; }
    }
}

In OnClientConnect() , the IAsyncResult object should have information on the client. Where you do ++m_clientCount; you could setup a dictionary with the unique info from each client and their ID (IP, port). Then in OnDataReceived() you could just GetClientID(Socket client) .

More info can be found on: https://msdn.microsoft.com/en-us/library/bbx2eya8(v=vs.110).aspx

Note that in the future, please post a simplest version of your issue, so that others don't have to go through the entire code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM