1. 程式人生 > >C#WinForm,TCP調試工具

C#WinForm,TCP調試工具

string read line thead internet items Coding 生命 except

Server端配置 參考代碼

1)設置基本參數


///
<summary> ///以本機作測試 /// </summary> private IPAddress serverIP = IPAddress.Parse("192.168.0.105"); /// <summary> ///完整終端地址 /// </summary> private IPEndPoint serverFullAddr; /// <summary> /// 連接套接字 /// </summary> private Socket sock;

2)啟動服務器端

serverIP = IPAddress.Parse(tbxIP.Text);
            
try { //設置IP和端口 serverFullAddr = new IPEndPoint(serverIP, int.Parse(tbxPort.Text)); sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //指定本地主機地址和端口號 sock.Connect(serverFullAddr); btnConn.Enabled
= false; MessageBox.Show("連接成功"); btnClose.Enabled = true; sock.Close(); } catch (Exception ee) {
           MessageBox.Show("連接失敗"+ee.ToString());
       }

3)停止服務端

 sock.Close();//關閉Socket連接

Client端 參考代碼

1)設置基本參數

  ///
<summary> /// 以本機作測試,IP /// </summary> private IPAddress serverIP = IPAddress.Parse("127.0.0.1"); /// <summary> /// 完整終端地址 /// </summary> private IPEndPoint serverFullAddr; /// <summary> /// 連接套接字 /// </summary> private Socket sock; /// <summary> /// 監聽線程 /// </summary> Thread myThead = null;

2)啟動服務器

  myThead = new Thread(new ThreadStart(BeginListen));
            myThead.Start();
            btnStart.Enabled = false;
            btnstop.Enabled = true;

3)設置偵聽

  /// <summary>
        /// 設置監聽
        /// </summary>
        private void BeginListen()
        {
            //IP
            serverIP = IPAddress.Parse(tbxIP.Text);
            //設置IP,端口
            serverFullAddr = new IPEndPoint(serverIP, int.Parse(tbxPort.Text));
            sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //指定本地主機地址和端口號
            sock.Bind(serverFullAddr);
            lbxMessage.Invoke(new SetTextCallback(SetText), "啟動成功 時間:" + DateTime.Now, 1);
            byte[] message = new byte[1024];
            string mess = "";
            while (true)
            {
                try
                {
                    sock.Listen(5);//設置監聽頻率
                    Socket newSocket = sock.Accept();//阻塞方式
                    int bytes = newSocket.Receive(message);//接收數據
                    mess = Encoding.Default.GetString(message, 0, bytes);//對接收字節編碼(S與C 兩端編碼格式必須一致不然中文亂碼)(當接收的字節大於1024的時候 這應該是循環接收,測試就沒有那樣寫了)
                    //do
                    //{
                    //    bytes = newSocket.Receive(message, message.Length, 0);
                    //    mess = mess + Encoding.ASCII.GetString(message, 0, bytes);
                    //}
                    //while (bytes > 0);

                    lbxMessage.Invoke(new SetTextCallback(SetText), mess, 1);//子線程操作主線程UI控件


                    //獲取客戶端的IP和端口
                    string ip11 = newSocket.RemoteEndPoint.AddressFamily.ToString();
                    
                    mess = "已接收數據: "+ mess +" 來自:" +ip11+ " 當前時間為:" + DateTime.Now; //處理數據
                    newSocket.Send(Encoding.Default.GetBytes(mess));//向客戶端發送數據

                }
                catch (SocketException se)
                {
                    lbxMessage.Invoke(new SetTextCallback(SetText), mess + se, 1);

                }
            }
        }

4)生命委托

   delegate void SetTextCallback(string text, int num);
        private void SetText(string text, int num)
        {
            lbxMessage.Items.Add(text);
        }

5)停止服務

 try
            {
                sock.Close();
                //中止監聽
                myThead.Abort();
                btnStart.Enabled = true;
                btnstop.Enabled = false;
                lbxMessage.Items.Add("停止成功 時間:" + DateTime.Now);
            }
            catch (Exception ee)
            {
                lbxMessage.Text = "停止失敗。。" + ee;
            }

5)接收消息

       private void Sending(IAsyncResult rec_socket)
        {
            //發送給客戶端的消息
            string sendmsg = "";
            Socket socket = (Socket)rec_socket.AsyncState;
            try
            {
                if (socket.Connected)
                {
                    byte[] msgBuff = Encoding.UTF8.GetBytes(sendmsg);
                    socket.Send(msgBuff);
                }
                else
                {
                    Console.WriteLine("Error!", "Error!");
                }
            }
            catch
            {
                Console.WriteLine("Error!", "Error!");
            }
        }

C#WinForm,TCP調試工具