C#實現局域網聊天 通信 Socket TCP 多人

程序分別爲服務端與客戶端,服務端建立套接字使用多線程偵聽多客戶端請求數組

代碼須要引用System.Net;和System.Net.Socket;這兩個類服務器

分享源碼demo:https://pan.baidu.com/s/10RuE9Vk0cIoxY91uzx4Gig     提取碼:4eds多線程

運行圖:ide

服務端函數

 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 }
展開查看代碼

客戶端spa

 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 }
展開查看代碼
相關文章
相關標籤/搜索