使用c#实现TCP客户端与服务器端

1、实现客户端:

(1)、 首先创建一个TCP客户端类:

这个类将包含连接到服务器、发送数据和接收数据的方法。

csharp 复制代码
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客户端类:

实例化这个类并使用它的方法来与服务器进行通信。

csharp 复制代码
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服务器类:

csharp 复制代码
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 client
                string 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)、实例化这个类并启动服务器:

csharp 复制代码
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();
        }
    }
}
相关推荐
geovindu3 分钟前
CSharp: Oracle Stored Procedure query table
数据库·oracle·c#·.net
yngsqq1 小时前
cad c# 二次开发 ——动态加载dll 文件制作(loada netloadx)
c#
吾与谁归in4 小时前
【C#联合halcon实现绘制ROI功能】
c#·halcon·roi
ling1s5 小时前
C#核心(18)面向对象多态vob
java·开发语言·c#
月巴月巴白勺合鸟月半6 小时前
一个C#开发的APP
c#·web
我曾经是个程序员7 小时前
C#File文件基础操作大全
开发语言·c#
三天不学习8 小时前
C# 中的记录类型简介 【代码之美系列】
后端·c#·微软技术·record·记录类型
Artistation Game8 小时前
一、c#基础
游戏·unity·c#·游戏引擎
chen_2278 小时前
kanzi3.6.10 窗口插件-查找绑定信息
c#·kanzi