• 网络调试工具编程实现


    1、界面设计
    在这里插入图片描述

    2、编程
    namespace NetWork
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }
    IPAddress ip;
    IPEndPoint point = new IPEndPoint(IPAddress.Any,0);
    string protocol;
    Socket aimSocket;
    Socket mySocket;
    UdpClient RecUdpClient;
    Thread thReceive = null;
    Boolean threadFlag = false;
    //初始化
    private void Form1_Load(object sender, EventArgs e)
    {
    cobProtocol.SelectedIndex = 0;
    txtIP.Text = GetAddressIP();
    Control.CheckForIllegalCrossThreadCalls = false;
    }
    string GetAddressIP()
    {
    string AddressIP = “”;
    foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
    {
    if (_IPAddress.AddressFamily.ToString() == “InterNetwork”)
    {
    AddressIP = _IPAddress.ToString();
    ip = _IPAddress;
    }
    }
    return AddressIP;
    }
    //打开按键处理函数
    private void btnStart_Click(object sender, EventArgs e)
    {
    if (btnStart.Text == “打开”)
    {
    btnStart.Enabled = false;
    threadFlag = true;
    ConnectNet();
    btnStart.Text = “关闭”;
    btnStart.Enabled = true;
    }
    else
    {
    btnStart.Enabled = false;
    threadFlag = false;
    CloseNet();
    btnStart.Text = “打开”;
    btnStart.Enabled = true;
    }

        }
    	//协议选择处理函数
        private void cobProtocol_SelectedIndexChanged(object sender, EventArgs e)
        {
            protocol = cobProtocol.SelectedItem.ToString();
            if (protocol == "UPD Server" || protocol == "TCP Server")
            {
                lblIP.Text = "本地IP地址:";
                lblPort.Text = "本地端口号:";
            }
            else if (protocol == "UDP Client" || protocol == "TCP Client")
            {
                lblIP.Text = "远程IP地址:";
                lblPort.Text = "远程端口号:";
            }
        }
    	//发送按键处理函数
        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] buffer = Encoding.Default.GetBytes(txtSend.Text);
                aimSocket.SendTo(buffer, point);
            }
            catch
            { }
        }
    	//连接网络
        private void ConnectNet()
        {
            try
            {
                if (protocol == "UDP Server")
                {
                    aimSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    RecUdpClient = new UdpClient(new IPEndPoint(ip, Convert.ToInt32(txtPort.Text)));
                    lbStatus.Text = "连接成功";
                    thReceive = new Thread(USReceive);
                    thReceive.IsBackground = true;
                    thReceive.Start();
                }
                else if (protocol == "UDP Client")//UPD客户端,目标IP和端口  调用Socket.SendTo
                {
                    aimSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//建立通信的Socket
                    ip = IPAddress.Parse(txtIP.Text);
                    point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));
                    lbStatus.Text = "连接成功";
                    thReceive = new Thread(UCReceive);
                    thReceive.IsBackground = true;
                    thReceive.Start();
                }
                else if (protocol == "TCP Server")
                {
                    mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));//绑定端口号
                    mySocket.Bind(point);//绑定监听端口
                    lbStatus.Text = "连接成功";
                    mySocket.Listen(10);//等待连接是一个阻塞过程,创建线程来监听
                    thReceive = new Thread(TSReceive);
                    thReceive.IsBackground = true;
                    thReceive.Start();
                }
                else if (protocol == "TCP Client")
                {
                    ip = IPAddress.Parse(txtIP.Text);//目标IP
                    point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));//目标端口
                    aimSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    aimSocket.Connect(point);//连接服务器
                    lbStatus.Text = "连接成功";
                    thReceive = new Thread(TCReceive);
                    thReceive.IsBackground = true;
                    thReceive.Start();
                }
    
            }
            catch(Exception exp)
            { 
                if(protocol == "UPD Server" || protocol == "TCP Server")
                {
                    mySocket.Close();
                }
                else if (protocol == "UDP Client" || protocol == "TCP Client")
                {
                    aimSocket.Close();
                }
                lbStatus.Text = "连接失败";
                Console.WriteLine(exp.Message);
            }
        }
    	//关闭网络
        private void CloseNet()
        {
            Thread.Sleep(1000);
            if (protocol == "UPD Server" || protocol == "TCP Server")
            {
                mySocket.Close();
                //mySocket.Dispose();
            }
            else if (protocol == "UDP Client" || protocol == "TCP Client")
            {
                aimSocket.Close();
            }
            lbStatus.Text = "连接关闭";
        }
    
        //TCP Server接收线程
        void TSReceive()
        {
            aimSocket = mySocket.Accept();//服务端监听到的Socket为服务端发送数据的目标socket
            byte[] buffer = new byte[1024];
            while (threadFlag)
            {
                try
                {
                    int r = aimSocket.Receive(buffer);//接收到监听的Socket的数据
                    if (r == 0)
                    {
                        break;
                    }
                    string strRec = Encoding.Default.GetString(buffer, 0, r);
                    txtRec.AppendText(aimSocket.RemoteEndPoint.ToString() + ":" + strRec + "\r\n");
                }
                catch
                { }
            }
        }
        //TCP Client接收线程
        void TCReceive()
        {           
            byte[] buffer = new byte[1024];
            while (threadFlag)
            {
                try
                { 
                    int r = aimSocket.Receive(buffer);
                    if (r == 0)
                    {
                        break;
                    }
                    string strRec = Encoding.Default.GetString(buffer, 0, r);
                    txtRec.AppendText(aimSocket.RemoteEndPoint.ToString() + ":" + strRec + "\r\n");
                }
                catch
                { }
            }
        }
        //UDP Clinet接收线程
        void UCReceive()
        {
            byte[] buffer = new byte[1024];
            while (true)
            {
                try
                {
                    IPEndPoint ss = new IPEndPoint(IPAddress.Any, 0);
                    EndPoint Remote = (EndPoint)(ss);
                    int r = aimSocket.ReceiveFrom(buffer, ref Remote);//接收目标IP Remote 发送过来的数
                    string strRec = Encoding.Default.GetString(buffer,0,r);
                    txtRec.AppendText(Remote.ToString() + ": " + strRec + "\r\n");
                }
                catch
                { }
            }
        }
        //UDP Server接收线程
        void USReceive()
        {
            while (true)
            {
                try
                {
                    byte[] buffer = RecUdpClient.Receive(ref point);
                    string strRec = Encoding.Default.GetString(buffer);
                    txtRec.AppendText(point.ToString() + ": " + strRec + "\r\n");
                }
                catch
                { }
            }
        }
    	//接收区域清除
        private void btRecClear_Click(object sender, EventArgs e)
        {
            txtRec.Clear();
        }
    	//发送区域清除
        private void btSendClear_Click(object sender, EventArgs e)
        {
            txtSend.Clear();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190

    }

    3、问题及解决
    以前在关闭网络中有线程Abort()函数,在频繁打开/关闭网络时经常出现异常,测试证明该方法结束线程并不可靠。
    解决办法:不终止线程,让线程自动退出。在线程函数中将while(true)换成While(flag),控制flag间接使线程退出。

  • 相关阅读:
    vue3中的组件实例和计算属性
    《Unity3D高级编程之进阶主程》第一章 C#要点技术(五) 排序算法
    C语言小游戏------贪吃蛇----小白专用
    C++使用spdlog输出日志文件
    K8S 极速入门
    GitHub私有派生仓库(fork仓库) | 派生仓库改为私有
    过滤器和拦截器的辨析
    栈的基本操作(C语言实现)
    520要来了,CSS3模拟3D旋转节日表白动画特效
    【面试题】Vue2为什么能通过this访问到data、methods的属性或方法
  • 原文地址:https://blog.csdn.net/qq_27474555/article/details/125428922