Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在WinC窗体中使用套接字连接在服务器端显示多个客户端名称#_C#_.net_Winforms - Fatal编程技术网

C# 在WinC窗体中使用套接字连接在服务器端显示多个客户端名称#

C# 在WinC窗体中使用套接字连接在服务器端显示多个客户端名称#,c#,.net,winforms,C#,.net,Winforms,在Windows窗体应用程序C#中,我使用套接字连接将多个客户端连接到单个服务器,并且我可以将多个客户端的号码发送到单个服务器。但问题是,在服务器上,我无法区分哪个客户端正在发送哪个号码,因此我需要在服务器端应用程序上以不同的方式显示client_1、client_2、client_3等等。请让我知道怎样会更好 服务器(在OnDataReceived()方法中,如何更改它?) 使用系统; 使用System.Collections.Generic; 使用系统组件模型; 使用系统数据; 使用系统图;

在Windows窗体应用程序C#中,我使用套接字连接将多个客户端连接到单个服务器,并且我可以将多个客户端的号码发送到单个服务器。但问题是,在服务器上,我无法区分哪个客户端正在发送哪个号码,因此我需要在服务器端应用程序上以不同的方式显示
client_1
client_2
client_3
等等。请让我知道怎样会更好

服务器(在OnDataReceived()方法中,如何更改它?)

使用系统;
使用System.Collections.Generic;
使用系统组件模型;
使用系统数据;
使用系统图;
使用System.IO;
使用System.Linq;
Net系统;
使用System.Net.Sockets;
使用系统文本;
使用系统线程;
使用System.Threading.Tasks;
使用System.Windows.Forms;
命名空间套接字服务器
{
公共部分类Form1:Form
{
const int MAX_CLIENTS=30;
公共异步回调pfnWorkerCallBack;
专用插座m_Main插座;
专用套接字[]m_workerSocket=新套接字[30];
private int m_clientCount=0;
公共图书馆;
公共表格1()
{
初始化组件();
}
私有void Form1\u加载(对象发送方、事件参数e)
{
字符串PortNumber=“1755”;
尝试
{
字符串portStr=PortNumber;
int port=System.Convert.ToInt32(portStr);
m_mainSocket=新套接字(AddressFamily.InterNetwork,
SocketType.Stream,
原型(Tcp);
IPEndPoint ipLocal=新IPEndPoint(IPAddress.Any,端口);
m_mainSocket.Bind(ipLocal);
m_mainSocket.听(4);
m_mainSocket.beginacept(新的异步回调(OnClientConnect)),null;
this.BackgroundWorker=新线程(新线程开始(Startinfiniteloop));
this.BackgroundWorker.Start();
}
捕获(SocketException se)
{
MessageBox.Show(se.Message);
}
}
public void Startinfiniteloop()
{
对于(int initial_value=0;initial_value++)
{
尝试
{
字典d2=新字典();
d2[“c2”]=初始值;
this.BeginInvoke((MethodInvoker)(()=>存储_Number.Items.Clear());
this.BeginInvoke((MethodInvoker)(()=>存储_Number.Items.Add(d2[“c2]”));
//延迟线程
睡眠(1000);
编号结束(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=新线程(新线程开始(NumberSend));
//this.BackgroundWorker.Start();
//STW=新的StreamWriter(发送[u Box.Items[初始值].ToString());
//STW.WriteLine(发送方框项目[初始值]);
//STW.AutoFlush=true;
}
捕获(异常x)
{
}
}
}
公共无效编号结束(字符串平均值)
{
尝试
{
对象objData=mesg;
byte[]byData=System.Text.Encoding.ASCII.GetBytes(objData.ToString());
对于(int i=0;itextBoxMsg.Clear());
调用(新操作(()=>textBoxMsg.AppendText(str));
m_mainSocket.beginacept(新的异步回调(OnClientConnect)),null;
}
捕获(ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0,“1”,“客户端连接:套接字已关闭\n”);
}
捕获(SocketException se)
{
MessageBox.Show(se.Message);
}
}
公共类SocketPacket
{
public System.Net.Sockets.Socket m_currentSocket;
公共字节[]数据缓冲=新字节[1024];
}
public void WaitForData(System.Net.Sockets.Socket soc)
{
尝试
{
if(pfnWorkerCallBack==null)
{
pfnWorkerCallBack=新的异步回调(OnDataReceived);
}
SocketPacket theSocPkt=新的SocketPacket();
socpkt.m_currentSocket=soc;//可能就是这个!!!
soc.BeginReceive(SOCPKT.dataBuffer,0,
theSocPkt.dataBuffer.Length,
SocketFlags,没有,
pfnWorkerCallBack,
 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; }
    }
}