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

运行结果:

猜你喜欢

转载自www.cnblogs.com/wq-KingStrong/p/10273705.html