C# TCP實現多個客戶端與服務端 數據 傳輸
實現一個客戶端和一個服務端通信
可以同時收發多條信息
使用C#語言,通過socket進行通信,基於TCP協議
服務端代碼:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Net; 7 using System.Net.Sockets; 8 using System.Threading; 9 10 namespace testServer 11 { 12 class Program 13 { 14 static void Main(string[] args) 15 { 16 Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//創建服務端 17 EndPoint point = new IPEndPoint(IPAddress.Prase("127.0.0.1"), 8888); 18 server.Bind(point);//綁定端口號和IP 19 server.Listen(10);//開啟監聽 20 Console.WriteLine("服務器開啟。。。。"); 21 Socket client = server.Accept();//保存連接進來的客戶端 22 client.Send(Encoding.UTF8.GetBytes("你已經進入服務"));//給客戶端發送消息,提示客戶端連接成功 23 24 25 Thread t1 = new Thread(reciveMsg); 26 t1.Start(client);//開啟線程接收消息 27 28 Thread t2 = new Thread(sendMsg); 29 t2.Start(client);//開啟線程發送消息 30 31 } 32 33 static void reciveMsg(object obj) 34 { 35 Socket client = obj as Socket; 36 while (true) 37 { 38 byte[] buffer = new byte[1024]; 39 try 40 { 41 int length = client.Receive(buffer); 42 string res = Encoding.UTF8.GetString(buffer, 0, length); 43 Console.WriteLine("接收到的消息:" + res); 44 } 45 catch (Exception e) 46 { 47 IPEndPoint point = client.RemoteEndPoint as IPEndPoint; 48 Console.WriteLine(point.ToString()+"斷開連接。。。"); 49 break; 50 } 51 52 } 53 54 } 55 56 static void sendMsg(object obj) 57 { 58 Socket client = obj as Socket; 59 while (true) 60 { 61 string s = Console.ReadLine(); 62 client.Send(Encoding.UTF8.GetBytes(s)); 63 } 64 } 65 } 66 }
客戶端代碼
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Net; 7 using System.Net.Sockets; 8 using System.Threading; 9 namespace testClient 10 { 11 class Program 12 { 13 static Socket client; 14 static Thread t1; 15 static Thread t2; 16 static bool isLife = false;//標記是否連接到服務器 17 static void Main(string[] args) 18 { 19 client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//創建客戶端 20 client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888));//將客戶端連接到服務器 21 22 23 isLife = true; 24 t1 = new Thread(reciveMsg); 25 t1.Start();//開啟線程接收消息 26 27 t2 = new Thread(sendMsg); 28 t2.Start();//開啟線程發送消息 29 30 //Console.ReadKey(); 31 } 32 33 static void reciveMsg() 34 { 35 while (isLife) 36 { 37 byte[] buffer = new byte[1024]; 38 try{ 39 int length = client.Receive(buffer); 40 string res = Encoding.UTF8.GetString(buffer, 0, length); 41 Console.WriteLine("接收到的消息:" + res); 42 }catch(Exception e){ 43 Console.WriteLine("reciveMsg: End"); 44 break; 45 } 46 47 } 48 49 } 50 51 static void sendMsg() { 52 while (isLife) 53 { 54 string s = Console.ReadLine(); 55 try { 56 client.Send(Encoding.UTF8.GetBytes(s)); 57 }catch (Exception e){ 58 Console.WriteLine("sendMsg: End"); 59 break; 60 } 61 62 if(s.Equals("886")){ 63 isLife = false; 64 client.Close(); 65 } 66 } 67 } 68 } 69 }
效果圖:
