网络传输:服务端与客户端

服务端UI:

namespace Test_TCP
{
    partial class Form1
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.tb_Port = new System.Windows.Forms.TextBox();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.label3 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.label4 = new System.Windows.Forms.Label();
            this.btn_State = new System.Windows.Forms.Button();
            this.btn_SendData = new System.Windows.Forms.Button();
            this.btn_StartListening = new System.Windows.Forms.Button();
            this.tb_CacheData = new System.Windows.Forms.TextBox();
            this.groupBox3 = new System.Windows.Forms.GroupBox();
            this.tb_Logs = new System.Windows.Forms.TextBox();
            this.groupBox1.SuspendLayout();
            this.groupBox2.SuspendLayout();
            this.groupBox3.SuspendLayout();
            this.SuspendLayout();
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(8, 50);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(65, 12);
            this.label1.TabIndex = 0;
            this.label1.Text = "监听端口:";
            // 
            // tb_Port
            // 
            this.tb_Port.Location = new System.Drawing.Point(79, 47);
            this.tb_Port.Name = "tb_Port";
            this.tb_Port.Size = new System.Drawing.Size(100, 21);
            this.tb_Port.TabIndex = 1;
            this.tb_Port.Text = "1200";
            // 
            // groupBox1
            // 
            this.groupBox1.Controls.Add(this.label3);
            this.groupBox1.Controls.Add(this.label2);
            this.groupBox1.Controls.Add(this.tb_Port);
            this.groupBox1.Controls.Add(this.label1);
            this.groupBox1.Location = new System.Drawing.Point(12, 12);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(193, 81);
            this.groupBox1.TabIndex = 2;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "配置";
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.label3.Location = new System.Drawing.Point(79, 20);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(47, 12);
            this.label3.TabIndex = 3;
            this.label3.Text = "0.0.0.0";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(8, 20);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(65, 12);
            this.label2.TabIndex = 2;
            this.label2.Text = "服务器IP:";
            // 
            // groupBox2
            // 
            this.groupBox2.Controls.Add(this.label4);
            this.groupBox2.Controls.Add(this.btn_State);
            this.groupBox2.Controls.Add(this.btn_SendData);
            this.groupBox2.Controls.Add(this.btn_StartListening);
            this.groupBox2.Controls.Add(this.tb_CacheData);
            this.groupBox2.Location = new System.Drawing.Point(12, 99);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(193, 198);
            this.groupBox2.TabIndex = 4;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "数据交互";
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(8, 77);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(41, 12);
            this.label4.TabIndex = 7;
            this.label4.Text = "数据:";
            // 
            // btn_State
            // 
            this.btn_State.Location = new System.Drawing.Point(121, 19);
            this.btn_State.Name = "btn_State";
            this.btn_State.Size = new System.Drawing.Size(27, 28);
            this.btn_State.TabIndex = 6;
            this.btn_State.UseVisualStyleBackColor = true;
            // 
            // btn_SendData
            // 
            this.btn_SendData.Location = new System.Drawing.Point(121, 71);
            this.btn_SendData.Name = "btn_SendData";
            this.btn_SendData.Size = new System.Drawing.Size(58, 25);
            this.btn_SendData.TabIndex = 5;
            this.btn_SendData.Text = "发送";
            this.btn_SendData.UseVisualStyleBackColor = true;
            // 
            // btn_StartListening
            // 
            this.btn_StartListening.Location = new System.Drawing.Point(10, 19);
            this.btn_StartListening.Name = "btn_StartListening";
            this.btn_StartListening.Size = new System.Drawing.Size(90, 28);
            this.btn_StartListening.TabIndex = 4;
            this.btn_StartListening.Text = "开始监听";
            this.btn_StartListening.UseVisualStyleBackColor = true;
            this.btn_StartListening.Click += new System.EventHandler(this.btn_StartListening_Click);
            // 
            // tb_CacheData
            // 
            this.tb_CacheData.Location = new System.Drawing.Point(10, 97);
            this.tb_CacheData.Multiline = true;
            this.tb_CacheData.Name = "tb_CacheData";
            this.tb_CacheData.ScrollBars = System.Windows.Forms.ScrollBars.Horizontal;
            this.tb_CacheData.Size = new System.Drawing.Size(169, 93);
            this.tb_CacheData.TabIndex = 1;
            this.tb_CacheData.Text = "test data ";
            // 
            // groupBox3
            // 
            this.groupBox3.Controls.Add(this.tb_Logs);
            this.groupBox3.Location = new System.Drawing.Point(211, 12);
            this.groupBox3.Name = "groupBox3";
            this.groupBox3.Size = new System.Drawing.Size(208, 285);
            this.groupBox3.TabIndex = 5;
            this.groupBox3.TabStop = false;
            this.groupBox3.Text = "日志";
            // 
            // tb_Logs
            // 
            this.tb_Logs.Location = new System.Drawing.Point(3, 17);
            this.tb_Logs.Multiline = true;
            this.tb_Logs.Name = "tb_Logs";
            this.tb_Logs.ScrollBars = System.Windows.Forms.ScrollBars.Horizontal;
            this.tb_Logs.Size = new System.Drawing.Size(202, 265);
            this.tb_Logs.TabIndex = 2;
            this.tb_Logs.Text = "The logs:";
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(427, 303);
            this.Controls.Add(this.groupBox3);
            this.Controls.Add(this.groupBox2);
            this.Controls.Add(this.groupBox1);
            this.MaximumSize = new System.Drawing.Size(443, 342);
            this.MinimumSize = new System.Drawing.Size(443, 39);
            this.Name = "Form1";
            this.Text = "TCP服务端";
            this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.Form1_FormClosed);
            this.Load += new System.EventHandler(this.Form1_Load);
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            this.groupBox2.ResumeLayout(false);
            this.groupBox2.PerformLayout();
            this.groupBox3.ResumeLayout(false);
            this.groupBox3.PerformLayout();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox tb_Port;
        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.GroupBox groupBox2;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.Button btn_State;
        private System.Windows.Forms.Button btn_SendData;
        private System.Windows.Forms.Button btn_StartListening;
        private System.Windows.Forms.TextBox tb_CacheData;
        private System.Windows.Forms.GroupBox groupBox3;
        private System.Windows.Forms.TextBox tb_Logs;
    }
}
UI:Form1

 服务端:

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

namespace Test_TCP
{
    public delegate void del_showInfo(string str);
    public partial class Form1 : Form
    {
      
      public del_showInfo hShowInfo_CallBack;

        TCPServer server;
        public Form1()
        {
            InitializeComponent();

            btn_StartListening.Tag = "0";
            hShowInfo_CallBack = new del_showInfo(UI_ShowInfo);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            server = new TCPServer();
            server.child_Showinfo = new del_showInfo(UpdateState_InThread);
        }

        private void btn_StartListening_Click(object sender, EventArgs e)
        {
            string tag = btn_StartListening.Tag.ToString();
            if (tag == "0")
            {
                btn_StartListening.Tag = "1";
                btn_State.BackColor = Color.Green;
                start();

                btn_StartListening.Enabled = false;
            }
            else
            {
                btn_StartListening.Tag = "0";
                btn_State.BackColor = Color.Red;
                stop();
            }
        }

        private void start()
        {
             string port = tb_Port.Text.Trim();

            server.Listen(int.Parse(port));
        }

        private void stop()
        {
            server.Stop();
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            server.Stop();
        }

        private void UI_ShowInfo(string str)
        {
            this.tb_Logs.AppendText(str+"\r\n");
        }

        public void UpdateState_InThread(string str)
        {
            //showInfo hShowInfo_CallBack = new showInfo(UI_ShowInfo);
            this.tb_Logs.Invoke(hShowInfo_CallBack, str);
        }
    }
}
Form1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Threading;
using System.Net;
using System.Net.Sockets;
namespace Test_TCP
{
    class TCPServer
    {
        private int port=1000;   //监听的端口(默认:1000)
        Thread listenThread;    //进程:监听请求
        Thread sonProcess;      //进程:监听数据

        Socket tcpSocket;
        List<Socket> clientSockets;
        bool flag_Listened = true;
        bool flag_RWData = true;

        public del_showInfo child_Showinfo;

        public TCPServer()
        {
            clientSockets = new List<Socket>();           
        }
        
        public void Listen(int input_port)
        {
            this.port = input_port;
            IPEndPoint serverSocket = new IPEndPoint(IPAddress.Any, port);

            tcpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//流套接字,TCP协议
            tcpSocket.Bind(serverSocket);   //将套接字与本地的某个节点绑定
            tcpSocket.Listen(10);

            ShowInfo("开始监听端口:"+port);
            ShowInfo("等待客户端连接:");

            listenThread = new Thread(ListenConnect);
            listenThread.Start(tcpSocket);

            flag_RWData = true;
            flag_Listened = true;
        }

        public void Stop()
        {
            flag_RWData = false;
            flag_Listened = false;

            tcpSocket.Close();
            if (sonProcess != null && sonProcess.IsAlive)
            {   
                sonProcess.Abort();
            }
            listenThread.Abort();
        }

        private void ListenConnect(object obj)
        {
            Socket tcpSocket = (Socket)obj;
            while(flag_Listened)
            {
                Socket client = tcpSocket.Accept(); //为新请求,创建socket!
                clientSockets.Add(client);          //更新用户群
                sonProcess= new Thread(acceptClient);
                sonProcess.Start(client);
            }
        }

        private void acceptClient(object client)
        {
            Socket socketClient = (Socket)client;
            IPEndPoint remoteIP = (IPEndPoint)socketClient.RemoteEndPoint;
            socketClient.Send(Encoding.UTF8.GetBytes("已连接到服务端的端口:" + port), SocketFlags.None);
            ShowInfo(string.Format("连接客户端({0}:{1})",remoteIP.Address,remoteIP.Port));   //日志

            while(flag_RWData)
            {//监控客户端的数据
                try
                {
                    byte[] recData = new byte[1024];
                    if (socketClient.Connected == false) { return; }
                    int longth = socketClient.Receive(recData);
                    string s = Encoding.UTF8.GetString(recData);
                    ShowInfo(string.Format("接收的数据:{0}",s));   //日志
                   

                    if(s.Trim().ToLower()=="exit")
                    {
                        ShowInfo(string.Format("客户端已脱机"));   //日志
                        clientSockets.Remove(socketClient);
                        socketClient.Close();
                        break;
                    }
                }
                catch (Exception e)
                {
                    ShowInfo("捕获异常!");
                    ShowInfo(e.Message.ToString());
                }
            }
        }

        //日志记录
        private void ShowInfo(string str)   
        {
            Console.WriteLine(str);
            child_Showinfo(str);
        }
    }
}
Test_TCP

 

客户端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

using System.Net;
using System.Net.Sockets;

namespace Test_TCP
{
    class TestClient
    {
        private static bool flag = true;    //true:连接正常,false:连接异常
        Socket newClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        string serverIP="127.0.0.1";
        int port = 1200;
        IPEndPoint server;
        string CacheData;

        public TestClient()
        {
            server = new IPEndPoint(IPAddress.Parse(serverIP), port);

            ConnectServer();
            
        }

        public void start()
        {
            Thread recThread = new Thread(receiveData);
            recThread.Start(newClient);
            SendData();
        }

        public bool ConnectServer()
        {
            try
            {
                newClient.Connect(server);
                byte[] data = new byte[1024];
                int recLength = newClient.Receive(data);
                string recData = Encoding.UTF8.GetString(data, 0, recLength);
                ShowInfo("首次连接,收到的数据:" + recData);

                return true;
            }
            catch (Exception e)
            {
                ShowInfo("连接服务器失败!");
                ShowInfo("错误信息:" + e.Message.ToString());
            }
            return false;
        }

        private void SendData()
        {
            while(true)
            {
                CacheData=Console.ReadLine();
                newClient.Send(Encoding.UTF8.GetBytes(CacheData), SocketFlags.None);
                if(CacheData=="exit")
                {
                    newClient.Close();
                    flag = false;
                    break;
                }
            }
        }

        private void receiveData(object obj)
        {
            Socket newClient = (Socket)obj;
            byte[] data = new byte[1024];
            while(flag==true)
            {
                try
                {
                    int length = newClient.Receive(data);
                    string s = Encoding.UTF8.GetString(data, 0, length);
                    ShowInfo(s);
                }
                catch (Exception)
                {
                    break;
                }
            }
        }

        //日志记录
        private void ShowInfo(string str)   
        {
            Console.WriteLine(str);
        }
    }
}
Test_TCP

 

 

posted @ 2023-04-06 14:46  冲云霄  阅读(1)  评论(0)    收藏  举报