C#socket編程之實現一個簡單的TCP通信


TCP(TransmissionControl Protocol)傳輸控制協議。

是一種可靠的、面向連接的協議(eg:打電話)、傳輸效率低全雙工通信(發送緩存&接收緩存)、面向字節流。使用TCP的應用:Web瀏覽器;電子郵件、文件傳輸程序。

TCP編程的服務器端一般步驟是:

  1、創建一個socket,用函數socket()。

  2、設置socket屬性。

  3、綁定本機的IP地址、端口等信息到socket上,用函數bind()。

  4、開啟監聽,用函數listen()。

      5、接收客戶端上來的連接,用函數accept()。

      6、通過accept()返回相應客戶端的socket建立專用的通信通道。

  7、收發數據,用函數send()和recv(),或者read()和write()。

  8、關閉網絡連接。

  9、關閉監聽。

TCP編程的客戶端一般步驟是:

  1、創建一個socket,用函數socket()。

  2、設置socket屬性。 

  3、設置要連接的對方的IP地址和端口等屬性。

  4、連接服務器,用函數connect()。

  5、收發數據,用函數send()和recv(),或者read()和write()。

  6、關閉網絡連接。 

---------------------
作者:subin_iecas
來源:CSDN
原文:https://blog.csdn.net/subin_iecas/article/details/80289513 

 

 


 

下面是一個簡單的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 _037_test
11 {
12     class Program
13     {
14         static void Main(string[] args)
15         {
16             Server s = new Server("192.168.0.105", 8888);
17             s.Start();
18         }
19     }
20 }
Program.CS
  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 _037_test
 11 {
 12     class Server
 13     {
 14         Socket serverSock;
 15         List<Socket> clientList = new List<Socket>();
 16         public Server(string ip, int port)
 17         {
 18             //創建socket套接字
 19             serverSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 20             //檢測ip地址是否有誤
 21             IPAddress ipAdd;
 22             if (!IPAddress.TryParse(ip, out ipAdd))
 23             {
 24                 Console.WriteLine("ip有誤,服務器創建失敗");
 25                 return;
 26             }
 27             //綁定ip地址和端口;
 28             IPEndPoint point = new IPEndPoint(ipAdd, port);
 29             serverSock.Bind(point);
 30             //無限監聽接收
 31             serverSock.Listen(0);
 32 
 33         }
 34 
 35         public void Start()
 36         {
 37             Thread th = new Thread(AcceptClient);
 38             th.Start();
 39             SendToAll();
 40         }
 41 
 42         public void AcceptClient()
 43         {
 44             Console.WriteLine("等待連接");
 45             while (true)
 46             {
 47                 Socket client = serverSock.Accept();//等待接收用戶的連接,並返回連接成功的用戶
 48                 IPEndPoint clientPoint = client.RemoteEndPoint as IPEndPoint;//獲取所連接的用戶的ip
 49                 Console.WriteLine(clientPoint.Address+"已連接");
 50                 clientList.Add(client);
 51                 Thread clientT = new Thread(ReceiveMessage);
 52                 clientT.Start(client);
 53             }
 54         }
 55 
 56         public void SendToAll()
 57         {
 58             while (true)
 59             {
 60                 string message = "管理員:"+Console.ReadLine();
 61                 byte[] messageBytes = Encoding.Default.GetBytes(message);
 62                 for (int i = 0; i < clientList.Count; i++)
 63                 {
 64                     try
 65                     {
 66                         clientList[i].Send(messageBytes);
 67                     }
 68                     catch (SocketException)
 69                     {
 70                         Console.WriteLine("有一個客戶端下線");
 71                         clientList.RemoveAt(i);
 72                         i--;
 73                     }
 74                     catch (Exception e)
 75                     {
 76                         Console.WriteLine(e.Message);
 77                     }
 78                 }
 79             }
 80         }
 81 
 82         public void ReceiveMessage(object obj)
 83         {
 84             while (true)
 85             {
 86                 Socket client = obj as Socket;//將線程的start方法傳入的obj轉回socket類型
 87                 byte[] messageBytes = new byte[100 * 1024];//數據容器
 88                 try
 89                 {
 90                     int num = client.Receive(messageBytes);//receive方法返回字節長度,並把內容存在傳入的數組中
 91                     IPEndPoint clientPoint = client.RemoteEndPoint as IPEndPoint;//獲取所連接的用戶的ip
 92                     Console.WriteLine(clientPoint.Address+"" + Encoding.Default.GetString(messageBytes, 0, num));
 93 
 94                     //服務器端負責將從客戶端收到的消息轉發給所有客戶端
 95                     string message = clientPoint.Address + ":" + Encoding.Default.GetString(messageBytes, 0, num);
 96                     foreach (var item in clientList)
 97                     {
 98                         if (item!=client)
 99                         {
100                             item.Send(Encoding.Default.GetBytes(message));
101                         }
102                     }
103                 }
104                 catch (Exception)
105                 {
106                     Console.WriteLine("有一個客戶端離開");
107                     clientList.Remove(client);
108                     break;
109                 }
110             }
111             
112         }
113     }
114 }
Server.CS

客戶端:

 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.Sockets;
 7 using System.Net;
 8 using System.Threading;
 9 
10 namespace _038_test
11 {
12     class Program
13     {
14         static void Main(string[] args)
15         {
16             Client c = new Client("192.168.0.105", 8888);
17             c.Start();
18         }
19     }
20 }
Program.CS
 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.Sockets;
 7 using System.Net;
 8 using System.Threading;
 9 
10 namespace _038_test
11 {
12     class Client
13     {
14         Socket clientSock;
15         public Client(string ip, int port)
16         {
17             clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
18             try
19             {
20                 IPEndPoint point = new IPEndPoint(IPAddress.Parse(ip), port);
21                 clientSock.Connect(point);
22             }
23             catch (Exception)
24             {
25                 Console.WriteLine("服務器沒有開啟");
26                 return;
27             }
28 
29             Console.WriteLine("已連接服務器");
30         }
31 
32         public void Start()
33         {
34             Thread th = new Thread(SendMessage);
35             th.Start();
36             ReceiveMessage();
37         }
38 
39         public void SendMessage()
40         {
41             try
42             {
43                 while (true)
44                 {
45                     string message = Console.ReadLine();
46                     byte[] messageBytes = Encoding.Default.GetBytes(message);
47                     clientSock.Send(messageBytes);
48                 }
49             }
50             catch (Exception)
51             {
52                 Console.WriteLine("服務器斷開");
53                 return;
54             }
55             
56         }
57 
58         public void ReceiveMessage()
59         {
60             try
61             {
62                 while (true)
63                 {
64                     byte[] messageBytes = new byte[100 * 1024];
65                     int num = clientSock.Receive(messageBytes);
66                     Console.WriteLine(Encoding.Default.GetString(messageBytes, 0, num));
67                 }
68             }
69             catch (Exception)
70             {
71                 Console.WriteLine("服務器斷開");
72                 return;
73             }
74         }
75 
76     }
77 }
Client.CS

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM