Halcom 发表于 2022-5-6 22:06:46

Socket网络通信基础教程【客户端/服务端】

Socket网络通信基础教程
      private void button1_Click(object sender, EventArgs e)
      {
            //Socket
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            string str0 = "Hello Client!";
            byte[] bytes0 = System.Text.Encoding.Default.GetBytes(str0);
            socket.Send(bytes0);
            socket.Blocking = false;

            //Connect
            string host = this.textBox1.Text.ToString();
            int port = int.Parse(this.textBox2.Text.ToString());
            socket.Connect(host, port);
            this.clientText.Text = "客户端地址" + socket.LocalEndPoint.ToString();

            int timesNoMsg = 0;
            if (socket.Available == 0)
            {
                Thread.Sleep(200);
                timesNoMsg++;
                if (timesNoMsg / 10 > timeOut)
                {
                  throw new Exception("连接中断");
                }
            }
            else
            {
                timesNoMsg = 0;
            }

            //Send
            string str = "Hello Unity!";
            byte[] bytes = System.Text.Encoding.Default.GetBytes(str);
            socket.Send(bytes);

            bool flag = true;
            //Recv
            while (flag == true)
            {
                int count = socket.Receive(readBuff);
                str = System.Text.Encoding.UTF8.GetString(readBuff, 0, count);
                if(str.Contains("_"))
                {

                }
                this.recvText.Text = str;
            }

            //Close
            socket.Close();
      }服务端接受 private void button1_Click(object sender, EventArgs e)
      {
            connfds = new Dictionary<string, Socket>();
            //方法
            Thread t = new Thread(new ThreadStart(listenProc));
            t.Start();
      }
      private void listenProc()
      {
            string ServerIP = this.textBox1.Text.ToString();
            int ServerPort = Convert.ToInt32(this.textBox2.Text.ToString());

            //新建一个套接字Socket即创建Socket
            Socket listenfd = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ipAdr = IPAddress.Any;
            IPEndPoint ipEp = new IPEndPoint(ipAdr, ServerPort);//用IPAddress指定的地址和端口号初始化

            listenfd.Bind(ipEp);
            listenfd.Listen(10);
            //Console.WriteLine("[服务器]启动成功");

            while (listening_)
            {
                //Accept
                Socket connfd = listenfd.Accept();
                string connGuid = Guid.NewGuid().ToString("B");
                connfds.Add(connGuid, connfd);
                //Console.WriteLine("[服务器]Accept");
                printmessage(Color.Blue, "[服务器]Accept");

                //Recv
                byte[] readBuff = new byte;
                int count = connfd.Receive(readBuff);
                string str = System.Text.Encoding.UTF8.GetString(readBuff, 0, count);
                //Console.WriteLine("[服务器接收]" + str);

                //Send

                byte[] bytes = System.Text.Encoding.Default.GetBytes("\r\n回传" + str);
                connfd.Send(bytes);

                // 对str操作
                string[] strs = str.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                bytes = System.Text.Encoding.Default.GetBytes("\r\n回传: " + strs);

                // 方法
                new Thread(() => BatchProc(connGuid, strs)).Start();

            }
      }

      private void BatchProc(string connGuid, string str)
      {
            //
            // 算法部分
            //

            if (connfds != null && connfds.Connected == true)
            {
                connfds.Send(System.Text.Encoding.Default.GetBytes("\r\n回传: " + "[图像检测完成]"));
                printmessage(Color.Blue, "[图像检测完成]" + str);
            }
      }


参考:
【1】C# Socket网络通信基础教程https://www.pianshen.com/article/4121438054/








页: [1]
查看完整版本: Socket网络通信基础教程【客户端/服务端】