1、实现客户端:
(1)、 首先创建一个TCP客户端类:
这个类将包含连接到服务器、发送数据和接收数据的方法。
using System;
using System.Net.Sockets;
using System.Text;public class TcpClientExample
{private TcpClient client;private NetworkStream stream;public TcpClientExample(string server, int port){client = new TcpClient(server, port);stream = client.GetStream();}//发送public void SendData(string data){byte[] dataToSend = Encoding.ASCII.GetBytes(data);stream.Write(dataToSend, 0, dataToSend.Length);Console.WriteLine($"Sent: {data}");}//接收public string ReceiveData(){byte[] buffer = new byte[256];int bytesRead = stream.Read(buffer, 0, buffer.Length);string responseData = Encoding.ASCII.GetString(buffer, 0, bytesRead);Console.WriteLine($"Received: {responseData}");return responseData;}//关闭连接public void CloseConnection(){stream.Close();client.Close();}
}
(2、使用TCP客户端类:
实例化这个类并使用它的方法来与服务器进行通信。
class Program
{static void Main(string[] args){string server = "127.0.0.1"; // 服务器的IP地址int port = 5000; // 服务器的端口号TcpClientExample tcpClient = new TcpClientExample(server, port);try{// 发送数据到服务器tcpClient.SendData("Hello, Server!");// 从服务器接收数据string response = tcpClient.ReceiveData();// 显示从服务器接收到的数据Console.WriteLine($"Server Response: {response}");}catch (Exception e){Console.WriteLine($"An error occurred: {e.Message}");}finally{// 关闭连接tcpClient.CloseConnection();}Console.WriteLine("Press any key to exit...");Console.ReadKey();}
}
2、实现服务器端:
(1)首先创建一个TCP服务器类:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;public class TcpServer
{private TcpListener listener;private bool isRunning;public TcpServer(int port){listener = new TcpListener(IPAddress.Any, port);isRunning = false;}public void Start(){listener.Start();isRunning = true;Console.WriteLine($"Server started on port {((IPEndPoint)listener.LocalEndpoint).Port}...");Task.Run(() => AcceptClientsAsync());}private async Task AcceptClientsAsync(){while (isRunning){try{TcpClient client = await listener.AcceptTcpClientAsync();Console.WriteLine("Client connected.");HandleClientAsync(client);}catch (ObjectDisposedException){// This exception may be thrown if the listener is stopped while accepting clients.break;}catch (Exception e){Console.WriteLine($"Error accepting client: {e.Message}");}}}private async Task HandleClientAsync(TcpClient client){NetworkStream stream = client.GetStream();byte[] buffer = new byte[1024];int bytesRead;try{while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0){string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);Console.WriteLine($"Received: {dataReceived}");// Send response to clientstring response = "Hello from server!";byte[] responseBytes = Encoding.ASCII.GetBytes(response);await stream.WriteAsync(responseBytes, 0, responseBytes.Length);}}catch (Exception e){Console.WriteLine($"Error handling client: {e.Message}");}finally{client.Close();Console.WriteLine("Client disconnected.");}}public void Stop(){isRunning = false;listener.Stop();Console.WriteLine("Server stopped.");}
}
(2)、实例化这个类并启动服务器:
class Program
{static void Main(string[] args){int port = 5000; // 服务器监听的端口号TcpServer server = new TcpServer(port);try{server.Start();Console.WriteLine("Press any key to stop the server...");Console.ReadKey();}finally{server.Stop();}}
}