程式分別為服務端與客戶端,服務端創建套接字使用多執行緒偵聽多客戶端請求
代碼需要參考System.Net;和System.Net.Socket;這兩個類
分享原始碼demo:https://pan.baidu.com/s/10RuE9Vk0cIoxY91uzx4Gig 提取碼:4eds
運行圖:

服務端
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace ConsoleServer 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 ServerControl Server = new ServerControl();//初始化Socket 13 Server.Start();//啟動偵聽連接 14 //Console.WriteLine("123"); 15 Console.Read(); 16 } 17 } 18 }展開查看代碼
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Net.Sockets; 6 using System.Net; 7 using System.Threading; 8 9 namespace ConsoleServer 10 { 11 public class ServerControl 12 { 13 public Socket ServerSocket; 14 public List<Socket> ClientList=null;//客戶端集合 15 16 /// <summary> 17 /// 建構式 18 /// </summary> 19 public ServerControl() 20 { 21 //創建套接字,ipv4尋址方式,套接字型別,傳輸協議 22 ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 23 ClientList=new List<Socket>();//實體化客戶端接入集合介入 24 } 25 26 public void Start() 27 { 28 ServerSocket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"),1231));//系結IP和埠 29 ServerSocket.Listen(10000);//支持最多連接數 30 Console.WriteLine("start server succeed"); 31 32 //當有客戶接入時當前執行緒會被掛起,每次新接入客戶端創建獨立線處理 33 Thread ThreadAccept = new Thread(Accept); 34 ThreadAccept.IsBackground = true;//設定為后臺執行緒 35 ThreadAccept.Start();//啟動執行緒 36 37 } 38 39 private void Accept() 40 { 41 Socket Client = ServerSocket.Accept();//客戶端接入當前執行緒掛起 42 IPEndPoint point=Client.RemoteEndPoint as IPEndPoint;//將遠端節點轉為ip和埠 43 Console.WriteLine("IP {0}:{1} connect succeed",point.Address,point.Port);//顯示接入資訊 44 ClientList.Add(Client);//將此連接添加到客戶集合 45 46 //接收訊息只處理一次,執行緒被掛起,創建新執行緒處理其新訊息 47 Thread ThreadReceive = new Thread(Receive); 48 ThreadReceive.IsBackground = true;//設定為后臺執行緒 49 ThreadReceive.Start(Client);//啟動執行緒 50 Accept();//回掉處理新接入客戶端 51 } 52 53 /// <summary> 54 /// 處理收到的訊息 55 /// </summary> 56 /// <param name="obj"></param> 57 private void Receive(object obj) 58 { 59 Socket Client = obj as Socket; 60 IPEndPoint point = Client.RemoteEndPoint as IPEndPoint;//將遠端節點轉為ip和埠 61 try 62 { 63 byte[] ByteReceive = new byte[1024];//訊息陣列 64 int ReceiveLenght = Client.Receive(ByteReceive);//只處理一次訊息,此處會被掛起 65 string msg = point.Address + "[" + point.Port + "]:" + Encoding.UTF8.GetString(ByteReceive, 0, ReceiveLenght); 66 Console.WriteLine(msg);//列印收到的訊息 67 Broadcast(Client, msg);//廣播訊息 68 69 Client.Send(Encoding.UTF8.GetBytes(DateTime.Now.ToString()));//回發當前時間給訊息源 70 Receive(Client);//回呼處理新訊息 71 } 72 catch 73 { 74 ClientList.Remove(Client);//當客戶端斷開,從客戶端集合移除該客戶端 75 Console.WriteLine("{0}[{1}]:斷開連接", point.Address, point);//列印提示資訊 76 } 77 78 } 79 80 /// <summary> 81 /// 廣播訊息 82 /// </summary> 83 /// <param name="cli"></param> 84 /// <param name="msg"></param> 85 public void Broadcast(Socket cli,string msg) 86 { 87 foreach (var item in ClientList )//遍歷所有客戶端 88 { 89 if (item != cli) 90 item.Send(Encoding.UTF8.GetBytes(msg));//給除資料源以外客戶端發送廣播訊息 91 } 92 } 93 } 94 }展開查看代碼
客戶端
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace ConsoleClient 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 ClientControl Client = new ClientControl();//初始化Socket 13 Client.Connect("127.0.0.1",1231);//連接到服務器 14 Console.WriteLine("Please enter the content to send,Enter exit to exit!");//提示資訊 15 string msg=Console.ReadLine();//輸入 16 while (msg!="exit")//判斷是否退出 17 { 18 Client.Send(msg);//發送訊息 19 msg = Console.ReadLine();//輸入訊息 20 21 } 22 23 } 24 } 25 }展開查看代碼
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Net.Sockets; 6 using System.Threading; 7 8 namespace ConsoleClient 9 { 10 public class ClientControl 11 { 12 private Socket ClientSocket; 13 14 public ClientControl() 15 { 16 //創建套接字,ipv4尋址方式,套接字型別,傳輸協議 17 ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 18 } 19 20 /// <summary> 21 /// 連接到服務器 22 /// </summary> 23 /// <param name="IP"></param> 24 /// <param name="Port"></param> 25 public void Connect(string IP, Int32 Port) 26 { 27 try 28 { 29 ClientSocket.Connect(IP, Port);//連接到指定服務器 30 Console.WriteLine("connect server succeed ok!");//提示資訊 31 //收到訊息是執行緒會被掛起,創建新執行緒處理收到的訊息 32 Thread ThreadReceive = new Thread(Receive); 33 ThreadReceive.IsBackground = true; 34 ThreadReceive.Start(); 35 } 36 catch(SocketException e) 37 { 38 Console.WriteLine("無法連接到{0}:{1}{2}",IP,Port,e); 39 } 40 } 41 42 /// <summary> 43 /// 發送訊息 44 /// </summary> 45 /// <param name="msg"></param> 46 public void Send(string msg) 47 { 48 ClientSocket.Send(Encoding.UTF8.GetBytes(msg)); 49 } 50 51 /// <summary> 52 /// 接收訊息 53 /// </summary> 54 private void Receive() 55 { 56 try 57 { 58 byte[] ByteReceive = new byte[1024]; 59 int ReceiveLenght = ClientSocket.Receive(ByteReceive);//此處執行緒會被掛起 60 Console.WriteLine("{0}", Encoding.UTF8.GetString(ByteReceive, 0, ReceiveLenght)); 61 Receive(); 62 } 63 catch 64 { 65 Console.WriteLine("服務器已斷開"); 66 } 67 } 68 } 69 }展開查看代碼
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/10276.html
標籤:其他
上一篇:程式員用實力把公司干倒閉了
