使用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();
        }
    }
}
相关推荐
SongYuLong的博客19 分钟前
C# (定时器、线程)
开发语言·c#
百锦再2 小时前
详解基于C#开发Windows API的SendMessage方法的鼠标键盘消息发送
windows·c#·计算机外设
无敌最俊朗@3 小时前
unity3d————协程原理讲解
开发语言·学习·unity·c#·游戏引擎
程序设计实验室3 小时前
在网页上调起本机C#程序
c#
Crazy Struggle6 小时前
.NET 8 强大功能 IHostedService 与 BackgroundService 实战
c#·.net·.net core
fs哆哆6 小时前
C#编程:优化【性别和成绩名次】均衡分班
开发语言·c#
fathing8 小时前
c# 调用c++ 的dll 出现找不到函数入口点
开发语言·c++·c#
wyh要好好学习10 小时前
C# WPF 记录DataGrid的表头顺序,下次打开界面时应用到表格中
开发语言·c#·wpf
AitTech10 小时前
C#实现:电脑系统信息的全面获取与监控
开发语言·c#
咩咩觉主10 小时前
尽量通俗易懂地概述.Net && U nity跨语言/跨平台相关知识
unity·c#·.net·.netcore