C# 中的 Socket 通信是通过 Socket 类来实现的。下面是一个简单的示例代码,演示了如何创建一个服务器和一个客户端,进行基本的 Socket 通信。\n\n服务器端代码:\n\ncsharp\nusing System;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Text;\n\nclass Program\n{\n static void Main()\n {\n // 创建一个服务器Socket对象\n Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n\n // 绑定IP地址和端口号\n IPAddress ipAddress = IPAddress.Parse("127.0.0.1");\n IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 1234);\n serverSocket.Bind(ipEndPoint);\n\n // 监听连接请求\n serverSocket.Listen(10);\n Console.WriteLine("Waiting for client connection...");\n\n // 接受客户端连接请求\n Socket clientSocket = serverSocket.Accept();\n Console.WriteLine("Client connected.");\n\n // 接收客户端发送的消息\n byte[] buffer = new byte[1024];\n int bytesRead = clientSocket.Receive(buffer);\n string message = Encoding.ASCII.GetString(buffer, 0, bytesRead);\n Console.WriteLine("Received message: " + message);\n\n // 发送响应给客户端\n string response = "Hello from server!";\n byte[] responseBytes = Encoding.ASCII.GetBytes(response);\n clientSocket.Send(responseBytes);\n\n // 关闭连接\n clientSocket.Shutdown(SocketShutdown.Both);\n clientSocket.Close();\n serverSocket.Close();\n\n Console.WriteLine("Connection closed.");\n }\n}\n\n\n客户端代码:\n\ncsharp\nusing System;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Text;\n\nclass Program\n{\n static void Main()\n {\n // 创建一个客户端Socket对象\n Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n\n // 连接服务器\n IPAddress ipAddress = IPAddress.Parse("127.0.0.1");\n IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 1234);\n clientSocket.Connect(ipEndPoint);\n Console.WriteLine("Connected to server.");\n\n // 发送消息给服务器\n string message = "Hello from client!";\n byte[] messageBytes = Encoding.ASCII.GetBytes(message);\n clientSocket.Send(messageBytes);\n\n // 接收服务器的响应\n byte[] buffer = new byte[1024];\n int bytesRead = clientSocket.Receive(buffer);\n string response = Encoding.ASCII.GetString(buffer, 0, bytesRead);\n Console.WriteLine("Received response: " + response);\n\n // 关闭连接\n clientSocket.Shutdown(SocketShutdown.Both);\n clientSocket.Close();\n\n Console.WriteLine("Connection closed.");\n }\n}\n\n\n这个示例中,服务器先启动并监听客户端连接请求,客户端连接后发送消息给服务器,服务器接收消息后发送响应给客户端。

C# Socket 通信教程:简单示例及代码

原文地址: https://www.cveoy.top/t/topic/qiu0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录