C# Socket服务端和客户端互相send和receive

本文详细介绍了TCP Socket通信的实现方式,包括服务端和客户端的代码示例。服务端监听特定端口并接受客户端连接,同时能够接收和发送消息。客户端则连接到服务端,接收服务端消息,并可以向服务端发送消息。
摘要由CSDN通过智能技术生成

服务端 

 1  using System;
 2  using System.Collections.Generic;
 3  using System.Text;
 4  using System.Net.Sockets;
 5  using System.Net;
 6  using System.Threading;
 7 
 8  namespace Controller
 9 {
10      public  static  class SocketServer
11     {
12          private  static  byte[] result =  new  byte[ 1024];
13          private  static  int myProt =  6000;    // 端口
14          private  static Socket serverSocket;
15          private  static List<Socket> clientSockets= new List<Socket>();
16          public  static  void Init()
17         {
18              // 服务器IP地址
19             IPAddress ip = IPAddress.Parse( " 127.0.0.1 ");
20             serverSocket =  new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
21             serverSocket.Bind( new IPEndPoint(ip, myProt));   // 绑定IP地址:端口
22             serverSocket.Listen( 10);     // 设定最多10个排队连接请求
23             Console.WriteLine( " 启动监听{0}成功 ", serverSocket.LocalEndPoint.ToString());
24              // 通过Clientsoket发送数据
25             Thread myThread =  new Thread(ListenClientConnect);
26             myThread.Start();
27             Console.ReadLine();
28         }
29 
30          ///   <summary>
31           ///  监听客户端连接
32           ///   </summary>
33          private  static  void ListenClientConnect()
34         {
35              while ( true)
36             {
37                 Socket clientSocket = serverSocket.Accept();
38                 clientSockets.Add(clientSocket);
39                 Thread receiveThread =  new Thread(ReceiveMessage);
40                 receiveThread.Start(clientSocket);
41             }
42         }
43 
44          ///   <summary>
45           ///  接收消息
46           ///   </summary>
47           ///   <param name="clientSocket"></param>
48          private  static  void ReceiveMessage( object clientSocket)
49         {
50             Socket myClientSocket = (Socket)clientSocket;
51              while ( true)
52             {
53                  try
54                 {
55                      // 通过clientSocket接收数据
56                      int receiveNumber = myClientSocket.Receive(result);
57                      string strContent = Encoding.ASCII.GetString(result,  0, receiveNumber);
58                     Console.WriteLine( " 接收客户端{0}消息{1} ", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result,  0, receiveNumber));
59                 }
60                  catch (Exception ex)
61                 {
62                     Console.WriteLine(ex.Message);
63                     myClientSocket.Shutdown(SocketShutdown.Both);
64                     myClientSocket.Close();
65                      break;
66                 }
67             }
68         }
69 
70          public  static  void SendMessage( string message)
71         {
72              foreach(Socket clientSocket  in clientSockets)
73                 clientSocket.Send(Encoding.ASCII.GetBytes(message));
74         }
75     }
76 }

客户端

 1  using System;
 2  using System.Collections.Generic;
 3  using System.Text;
 4  using System.Net.Sockets;
 5  using System.Net;
 6  using System.Threading;
 7 
 8  namespace Player
 9 {
10      public  static  class SocketClient
11     {
12          private  static Socket clientSocket =  new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
13          private  static  byte[] result =  new  byte[ 1024];
14          public  static  void Init()
15         {
16              // 设定服务器IP地址
17             IPAddress ip = IPAddress.Parse( " 127.0.0.1 ");            
18              try
19             {
20                 clientSocket.Connect( new IPEndPoint(ip,  6000));  // 配置服务器IP与端口
21                 Console.WriteLine( " 连接服务器成功 ");
22             }
23              catch
24             {
25                 Console.WriteLine( " 连接服务器失败,请按回车键退出! ");
26                  return;
27             }
28 
29             Thread receiveThread =  new Thread(ReceiveMessage);
30             receiveThread.Start();
31             
32         }
33          ///   <summary>
34           ///  接收消息
35           ///   </summary>
36           ///   <param name="clientSocket"></param>
37          private  static  void ReceiveMessage()
38         {            
39              while ( true)
40             {
41                  try
42                 {
43                      // 通过clientSocket接收数据
44                      int receiveNumber = clientSocket.Receive(result);
45                      string strContent = Encoding.ASCII.GetString(result,  0, receiveNumber);
46                     Console.WriteLine( " 接收服务端{0}消息{1} ", clientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result,  0, receiveNumber));
47                 }
48                  catch (Exception ex)
49                 {
50                     Console.WriteLine(ex.Message);
51                     clientSocket.Shutdown(SocketShutdown.Both);
52                     clientSocket.Close();
53                      break;
54                 }
55             }
56         }
57          public  static  void SendMessage( string message)
58         {
59              string sendMessage = message;
60             clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage));
61         }
62     }
63 }

 

转载于:https://www.cnblogs.com/erictanghu/p/3721045.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值