Browse Source

TCP通讯demo修改

Hcsy 6 years ago
parent
commit
f90174deba
2 changed files with 145 additions and 15 deletions
  1. 89 5
      PLCDataReader/ClassFile/ModeBusTCPServer.cs
  2. 56 10
      PLCDataReader/MainWindow.Designer.cs

+ 89 - 5
PLCDataReader/ClassFile/ModeBusTCPServer.cs

@@ -1,4 +1,5 @@
 using System;
+using System.Collections.Generic;
 using System.Net;
 using System.Net.Sockets;
 using System.Text;
@@ -59,6 +60,13 @@ namespace ClassFile
         private string port;
 
         RichTextAutoBottom richtext;
+        ComboBox SelectIP;
+
+        Button SEND;
+        RichTextAutoBottom SENDMESSAGE;
+        public List<Socket> list = new List<Socket>();
+
+        private Boolean messageflag = false;
 
         public ModeBusTCPServer()
         {
@@ -69,7 +77,11 @@ namespace ClassFile
         {
             try
             {
+                SelectIP = Application.OpenForms["MainWindow"].Controls["SelectIP"] as ComboBox;
                 richtext = Application.OpenForms["MainWindow"].Controls["Result"] as RichTextAutoBottom;
+                SEND = Application.OpenForms["MainWindow"].Controls["SEND"] as Button;
+                SENDMESSAGE = Application.OpenForms["MainWindow"].Controls["SENDMESSAGE"] as RichTextAutoBottom;
+                SEND.Click += SEND_Click;
                 //定义一个套接字用于监听客户端发来的信息  包含3个参数(IP4寻址协议,流式连接,TCP协议)
                 socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                 //服务端发送信息 需要1个IP地址和端口号
@@ -96,6 +108,37 @@ namespace ClassFile
             }
         }
 
+        private void SEND_Click(object sender, EventArgs e)
+        {
+            foreach (Socket item in list)
+            {
+                if (item != null)
+                {
+                    if (item.RemoteEndPoint != null)
+                    {
+                        if (item.RemoteEndPoint.ToString() == SelectIP.Text)
+                        {
+                            item.Send(Encoding.UTF8.GetBytes("\n" + SENDMESSAGE.Text));
+                        }
+                    }
+                    else
+                    {
+                        int index = SelectIP.Items.IndexOf(item.RemoteEndPoint.ToString());
+                        SelectIP.Items.RemoveAt(index);
+                        SelectIP.Update();
+                        richtext.AppendText("客户端" + item.RemoteEndPoint + "已经中断连接" + "\r\n");
+
+                        if (list.Contains(item))
+                        {
+                            list.Remove(item);
+                        }
+                        //关闭之前accept出来的和客户端进行通信的套接字 
+                        item.Close();
+                    }
+                }
+            }
+        }
+
         private void WatchConnecting()
         {
             Socket connection = null;
@@ -122,7 +165,8 @@ namespace ClassFile
                 string remoteEndPoint = connection.RemoteEndPoint.ToString();
                 //显示与客户端连接情况
                 richtext.AppendText("成功与" + remoteEndPoint + "客户端建立连接!\t\n");
-
+                SelectIP.Items.Add(clientIP + ":" + clientPort.ToString());
+                SelectIP.SelectedItem = clientIP + ":" + clientPort.ToString();
                 //IPEndPoint netpoint = new IPEndPoint(clientIP,clientPort); 
                 IPEndPoint netpoint = connection.RemoteEndPoint as IPEndPoint;
 
@@ -133,9 +177,21 @@ namespace ClassFile
                 thread.IsBackground = true;
                 //启动线程     
                 thread.Start(connection);
+
+                //创建一个通信线程
+                //ParameterizedThreadStart sed = new ParameterizedThreadStart(sends);
+                //Thread threadsed = new Thread(sed);
+                //设置为后台线程,随着主线程退出而退出
+                //threadsed.IsBackground = true;
+                //启动线程
+                //threadsed.Start(connection);
+
+                list.Add(connection);
+
             }
         }
 
+
         void recv(object socketclientpara)
         {
             Socket socketServer = socketclientpara as Socket;
@@ -147,21 +203,49 @@ namespace ClassFile
                 try
                 {
                     int length = socketServer.Receive(arrServerRecMsg);
+                    if (length == 0)
+                    {
+                        break;
+                    }
                     //将机器接受到的字节数组转换为人可以读懂的字符串     
                     string strSRecMsg = Encoding.UTF8.GetString(arrServerRecMsg, 0, length);
                     //将发送的字符串信息附加到文本框txtMsg上     
                     richtext.AppendText("客户端:" + socketServer.RemoteEndPoint + ",\r\n" + strSRecMsg + "\r\n\n");
-                    socketServer.Send(Encoding.UTF8.GetBytes("ReturnData"));
                 }
-                catch (Exception ex)
+                catch (Exception)
                 {
-                    //提示套接字监听异常  
-                    richtext.AppendText("客户端" + socketServer.RemoteEndPoint + "已经中断连接" + "\r\n" + ex.Message + "\r\n" + ex.StackTrace + "\r\n");
+                    if (socketServer.RemoteEndPoint != null)
+                    {
+                        //提示套接字监听异常  
+                        int index = SelectIP.Items.IndexOf(socketServer.RemoteEndPoint.ToString());
+                        SelectIP.Items.RemoveAt(index);
+                        SelectIP.Update();
+                        richtext.AppendText("客户端" + socketServer.RemoteEndPoint + "已经中断连接" + "\r\n");
+                    }
+                    if (list.Contains(socketServer))
+                    {
+                        list.Remove(socketServer);
+                    }
                     //关闭之前accept出来的和客户端进行通信的套接字 
                     socketServer.Close();
                     break;
                 }
             }
+            if (socketServer != null)
+            {
+                if (socketServer.RemoteEndPoint != null)
+                {
+                    int index = SelectIP.Items.IndexOf(socketServer.RemoteEndPoint.ToString());
+                    SelectIP.Items.RemoveAt(index);
+                    SelectIP.Update();
+                    richtext.AppendText("客户端" + socketServer.RemoteEndPoint + "已经中断连接" + "\r\n");
+                }
+                if (list.Contains(socketServer))
+                {
+                    list.Remove(socketServer);
+                }
+                socketServer.Close();
+            }
         }
 
         public void Close()

+ 56 - 10
PLCDataReader/MainWindow.Designer.cs

@@ -34,22 +34,26 @@
             this.Port = new System.Windows.Forms.TextBox();
             this.OpenServer = new System.Windows.Forms.Button();
             this.CloseServer = new System.Windows.Forms.Button();
+            this.SelectIP = new System.Windows.Forms.ComboBox();
+            this.SEND = new System.Windows.Forms.Button();
+            this.IPTEXT = new System.Windows.Forms.Label();
+            this.SENDMESSAGE = new UAS_PLCDataReader.RichTextAutoBottom();
             this.Result = new UAS_PLCDataReader.RichTextAutoBottom();
             this.SuspendLayout();
             // 
             // IP
             // 
             this.IP.Enabled = false;
-            this.IP.Location = new System.Drawing.Point(111, 328);
+            this.IP.Location = new System.Drawing.Point(103, 325);
             this.IP.Name = "IP";
-            this.IP.Size = new System.Drawing.Size(133, 21);
+            this.IP.Size = new System.Drawing.Size(103, 21);
             this.IP.TabIndex = 0;
             // 
             // IP_label
             // 
             this.IP_label.AutoSize = true;
             this.IP_label.Font = new System.Drawing.Font("微软雅黑", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
-            this.IP_label.Location = new System.Drawing.Point(12, 328);
+            this.IP_label.Location = new System.Drawing.Point(12, 325);
             this.IP_label.Name = "IP_label";
             this.IP_label.Size = new System.Drawing.Size(85, 21);
             this.IP_label.TabIndex = 1;
@@ -59,7 +63,7 @@
             // 
             this.Port_label.AutoSize = true;
             this.Port_label.Font = new System.Drawing.Font("微软雅黑", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
-            this.Port_label.Location = new System.Drawing.Point(255, 328);
+            this.Port_label.Location = new System.Drawing.Point(212, 325);
             this.Port_label.Name = "Port_label";
             this.Port_label.Size = new System.Drawing.Size(42, 21);
             this.Port_label.TabIndex = 3;
@@ -67,14 +71,14 @@
             // 
             // Port
             // 
-            this.Port.Location = new System.Drawing.Point(314, 328);
+            this.Port.Location = new System.Drawing.Point(260, 325);
             this.Port.Name = "Port";
-            this.Port.Size = new System.Drawing.Size(133, 21);
+            this.Port.Size = new System.Drawing.Size(105, 21);
             this.Port.TabIndex = 2;
             // 
             // OpenServer
             // 
-            this.OpenServer.Location = new System.Drawing.Point(496, 328);
+            this.OpenServer.Location = new System.Drawing.Point(371, 323);
             this.OpenServer.Name = "OpenServer";
             this.OpenServer.Size = new System.Drawing.Size(65, 23);
             this.OpenServer.TabIndex = 4;
@@ -84,7 +88,7 @@
             // 
             // CloseServer
             // 
-            this.CloseServer.Location = new System.Drawing.Point(597, 328);
+            this.CloseServer.Location = new System.Drawing.Point(442, 323);
             this.CloseServer.Name = "CloseServer";
             this.CloseServer.Size = new System.Drawing.Size(65, 23);
             this.CloseServer.TabIndex = 5;
@@ -92,11 +96,45 @@
             this.CloseServer.UseVisualStyleBackColor = true;
             this.CloseServer.Click += new System.EventHandler(this.CloseServer_Click);
             // 
+            // SelectIP
+            // 
+            this.SelectIP.FormattingEnabled = true;
+            this.SelectIP.Location = new System.Drawing.Point(531, 64);
+            this.SelectIP.Name = "SelectIP";
+            this.SelectIP.Size = new System.Drawing.Size(159, 20);
+            this.SelectIP.TabIndex = 7;
+            // 
+            // SEND
+            // 
+            this.SEND.Location = new System.Drawing.Point(573, 323);
+            this.SEND.Name = "SEND";
+            this.SEND.Size = new System.Drawing.Size(75, 23);
+            this.SEND.TabIndex = 9;
+            this.SEND.Text = "SEND";
+            this.SEND.UseVisualStyleBackColor = true;
+            // 
+            // IPTEXT
+            // 
+            this.IPTEXT.AutoSize = true;
+            this.IPTEXT.Location = new System.Drawing.Point(531, 24);
+            this.IPTEXT.Name = "IPTEXT";
+            this.IPTEXT.Size = new System.Drawing.Size(53, 12);
+            this.IPTEXT.TabIndex = 10;
+            this.IPTEXT.Text = "已连接IP";
+            // 
+            // SENDMESSAGE
+            // 
+            this.SENDMESSAGE.Location = new System.Drawing.Point(531, 120);
+            this.SENDMESSAGE.Name = "SENDMESSAGE";
+            this.SENDMESSAGE.Size = new System.Drawing.Size(159, 202);
+            this.SENDMESSAGE.TabIndex = 8;
+            this.SENDMESSAGE.Text = "";
+            // 
             // Result
             // 
             this.Result.Location = new System.Drawing.Point(12, 12);
             this.Result.Name = "Result";
-            this.Result.Size = new System.Drawing.Size(678, 310);
+            this.Result.Size = new System.Drawing.Size(486, 310);
             this.Result.TabIndex = 6;
             this.Result.Text = "";
             // 
@@ -105,6 +143,10 @@
             this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
             this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
             this.ClientSize = new System.Drawing.Size(702, 358);
+            this.Controls.Add(this.IPTEXT);
+            this.Controls.Add(this.SEND);
+            this.Controls.Add(this.SENDMESSAGE);
+            this.Controls.Add(this.SelectIP);
             this.Controls.Add(this.Result);
             this.Controls.Add(this.CloseServer);
             this.Controls.Add(this.OpenServer);
@@ -117,7 +159,7 @@
             this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
             this.Text = "PLCDataReader";
             this.Load += new System.EventHandler(this.Form1_Load);
-            this.ResumeLayout(false);
+            this.ResumeLayout(true);
             this.PerformLayout();
 
         }
@@ -131,6 +173,10 @@
         private System.Windows.Forms.Button OpenServer;
         private System.Windows.Forms.Button CloseServer;
         private RichTextAutoBottom Result;
+        private System.Windows.Forms.ComboBox SelectIP;
+        private RichTextAutoBottom SENDMESSAGE;
+        private System.Windows.Forms.Button SEND;
+        private System.Windows.Forms.Label IPTEXT;
     }
 }