服务器端代码
using System; using System.Net; using System.Net.Sockets; using System.Text; class Program { static void Main(string[] args) { // 创建IPEndPoint实例,指定服务器的IP地址和端口号 IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Any, 12345); // 创建Socket对象 Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 将Socket绑定到指定的IPEndPoint serverSocket.Bind(serverEndPoint); // 开始监听连接请求 serverSocket.Listen(10); Console.WriteLine("服务器已启动,等待客户端连接..."); while (true) { // 接受客户端的连接请求 Socket clientSocket = serverSocket.Accept(); Console.WriteLine("客户端已连接:" + clientSocket.RemoteEndPoint.ToString()); // 从客户端接收数据 byte[] buffer = new byte[1024]; int bytesReceived = clientSocket.Receive(buffer, 0, buffer.Length, 0); if (bytesReceived > 0) { string receivedData = Encoding.UTF8.GetString(buffer, 0, bytesReceived); Console.WriteLine("收到客户端消息:" + receivedData); // 向客户端发送响应数据 string responseData = "服务器已收到消息:" + receivedData; byte[] responseBuffer = Encoding.UTF8.GetBytes(responseData); clientSocket.Send(responseBuffer, 0, responseBuffer.Length, 0); } // 关闭与该客户端的连接 clientSocket.Close(); } } }
客户端代码
using System; using System.Net.Sockets; using System.Text; class Program { static void Main(string[] args) { // 创建IPEndPoint实例,指定服务器的IP地址和端口号 IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12345); // 创建Socket对象 Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 连接到服务器 clientSocket.Connect(serverEndPoint); Console.WriteLine("已连接到服务器:" + serverEndPoint.ToString()); // 向服务器发送数据 string sendData = "Hello, Server!"; byte[] sendBuffer = Encoding.UTF8.GetBytes(sendData); clientSocket.Send(sendBuffer, 0, sendBuffer.Length, 0); Console.WriteLine("已发送消息到服务器:" + sendData); // 从服务器接收数据 byte[] receiveBuffer = new byte[1024]; int bytesReceived = clientSocket.Receive(receiveBuffer, 0, receiveBuffer.Length, 0); if (bytesReceived > 0) { string receivedData = Encoding.UTF8.GetString(receiveBuffer, 0, bytesReceived); Console.WriteLine("收到服务器响应:" + receivedData); } // 关闭与服务器的连接 clientSocket.Close(); } }
相关问答FAQs
问题一:如何修改服务器端的监听端口?
答:在服务器端代码中,通过修改IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Any, 12345);
这一行中的端口号即可,如果你想将端口号改为8080,只需将该行修改为IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Any, 8080);
,客户端代码中也需要将对应的端口号修改为相同的值,以确保能够正确连接到服务器。
问题二:如果服务器端没有及时处理客户端的连接请求,客户端会一直等待吗?
答:是的,在上述示例代码中,客户端会一直等待直到服务器端接受连接请求或者出现超时错误,如果在实际应用中需要设置超时时间,可以在客户端代码中使用Socket.Connect
方法的重载版本,传入一个TimeSpan
参数来指定超时时间。clientSocket.Connect(serverEndPoint, TimeSpan.FromSeconds(5));
这样客户端在尝试连接服务器5秒后仍未成功连接,就会抛出超时异常,避免客户端一直等待。
原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/1533213.html
本网站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。
发表回复