1. 服务器端代码
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Net; 5 using System.Net.Sockets; 6 using System.Text; 7 using System.Threading; 8 using System.Threading.Tasks; 9 10 namespace Sever 11 { 12 class Program 13 { 14 private static Socket severSocket = null; 15 16 /// <summary> 17 /// 服务端程序 18 /// 1. 新建 socket,并绑定端口 19 /// 2. 接收客户端连接 20 /// 3. 给客户端发送信息 21 /// 4. 接收客户端信息 22 /// 5. 断开连接 23 /// </summary> 24 /// <param name="args"></param> 25 static void Main(string[] args) 26 { 27 severSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 28 IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 9999); 29 severSocket.Bind(endPoint); // 绑定 30 severSocket.Listen(10); // 设置最大连接数 31 Console.WriteLine("开始监听"); 32 Thread thread = new Thread(ListenClientConnect); // 开启线程监听客户端连接 33 thread.Start(); 34 Console.ReadKey(); 35 } 36 37 /// <summary> 38 /// 监听客户端连接 39 /// </summary> 40 private static void ListenClientConnect() 41 { 42 Socket clientSocket = severSocket.Accept(); // 接收客户端连接 43 Console.WriteLine("客户端连接成功 信息: " + clientSocket.AddressFamily.ToString()); 44 clientSocket.Send(Encoding.Default.GetBytes("你连接成功了")); 45 Thread revThread = new Thread(ReceiveClientManage); 46 revThread.Start(clientSocket); 47 } 48 49 private static void ReceiveClientManage(object clientSocket) 50 { 51 Socket socket = clientSocket as Socket; 52 byte[] buffer = new byte[1024]; 53 int length = socket.Receive(buffer); // 从客户端接收消息 54 Console.WriteLine("收到消息:" + Encoding.Default.GetString(buffer)); 55 } 56 } 57 }
2. 客户端代码
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Net; 5 using System.Net.Sockets; 6 using System.Text; 7 using System.Threading.Tasks; 8 9 namespace client 10 { 11 /// <summary> 12 /// 客户端程序 13 /// 1. 新建 Socket 14 /// 2. 连接服务器 15 /// 3. 接收服务器信息 16 /// 4. 向服务器发送信息 17 /// </summary> 18 class Program 19 { 20 private static Socket clientSocket = null; 21 22 static void Main(string[] args) 23 { 24 clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 25 // 客户端不需要绑定, 需要连接 26 IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999); // 端口号要与服务器对应 27 clientSocket.Connect(endPoint); 28 Console.WriteLine("连接到服务器"); 29 // 接收服务器信息 30 byte[] buffer = new byte[1024]; 31 int length = clientSocket.Receive(buffer); 32 Console.WriteLine("收到消息: " + Encoding.Default.GetString(buffer)); 33 // 向服务器发送消息 34 clientSocket.Send(Encoding.Default.GetBytes("你好服务器")); 35 Console.ReadKey(); 36 } 37 } 38 }
3. 运行截图