1. 程式人生 > >c# 使用TCP連接(server)

c# 使用TCP連接(server)

客戶 綁定 cnblogs start click nbsp mar summary color

效果圖

技術分享

代碼實現

用的變量:

1      Thread threadWatch = null; //負責監聽客戶端的線程
2         Socket socketWatch = null; //負責監聽客戶端的套接字
3         //創建一個負責和客戶端通信的套接字 
4         List<Socket> socConnections = new List<Socket>();
5         List<Thread> dictThread = new List<Thread>();

啟動服務按鈕代碼如下:

 1 private void btnServerConn_Click(object sender, EventArgs e)
 2         {
 3             //定義一個套接字用於監聽客戶端發來的信息  包含3個參數(IP4尋址協議,流式連接,TCP協議)
 4             socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 5             //服務端發送信息 需要1個IP地址和端口號
 6             IPAddress ipaddress = IPAddress.Parse(txtIP.Text.Trim()); //
獲取文本框輸入的IP地址 7 //將IP地址和端口號綁定到網絡節點endpoint上 8 IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse(txtPORT.Text.Trim())); //獲取文本框上輸入的端口號 9 //監聽綁定的網絡節點 10 socketWatch.Bind(endpoint); 11 //將套接字的監聽隊列長度限制為20 12 socketWatch.Listen(20
); 13 //創建一個監聽線程 14 threadWatch = new Thread(WatchConnecting); 15 //將窗體線程設置為與後臺同步 16 threadWatch.IsBackground = true; 17 //啟動線程 18 threadWatch.Start(); 19 //啟動線程後 txtMsg文本框顯示相應提示 20 txtMsg.AppendText("開始監聽客戶端傳來的信息!" + "\r\n"); 21 22 }

監聽客戶端消息代碼如下:

 1      /// <summary>
 2         /// 監聽客戶端發來的請求
 3         /// </summary>
 4         private void WatchConnecting()
 5         {
 6             while (true)  //持續不斷監聽客戶端發來的請求
 7             {
 8                 Socket socConnection = socketWatch.Accept();
 9                 txtMsg.AppendText("客戶端連接成功" + "\r\n");
10                 //創建一個通信線程 
11                 ParameterizedThreadStart pts = new ParameterizedThreadStart(ServerRecMsg);
12                 Thread thr = new Thread(pts);
13                 thr.IsBackground = true;
14                 socConnections.Add(socConnection);
15                 //啟動線程
16                 thr.Start(socConnection);
17                 dictThread.Add(thr);
18             }
19         }

將消息發送到客戶端

 1      //發送信息到客戶端
 2         private void btnSendMsg_Click(object sender, EventArgs e)
 3         {
 4             //調用 ServerSendMsg方法  發送信息到客戶端
 5             ServerSendMsg(txtSendMsg.Text.Trim());
 6         }
 7 
 8         /// <summary>
 9         /// 發送信息到客戶端的方法
10         /// </summary>
11         /// <param name="sendMsg">發送的字符串信息</param>
12         private void ServerSendMsg(string sendMsg)
13         {
14             //將輸入的字符串轉換成 機器可以識別的字節數組
15             byte[] arrSendMsg = Encoding.UTF8.GetBytes(sendMsg);
16             //向客戶端發送字節數組信息
17             foreach (Socket socConnection in socConnections)
18             {
19                 socConnection.Send(arrSendMsg);
20             }
21 
22             //將發送的字符串信息附加到文本框txtMsg上
23             txtMsg.AppendText("So-flash:" + GetCurrentTime() + "\r\n" + sendMsg + "\r\n");
24             //}
25 
26         }

c# 使用TCP連接(server)