C#中编写TCP客户端和服务端

在C#中编写TCP客户端和服务端涉及到System.Net.Sockets命名空间中的TcpListener和TcpClient类。下面分别给出一个简单的TCP服务端和客户端的示例代码。


using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class TcpServer
{
    public static void StartServer()
    {
        // 监听的IP和端口
        IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
        int port = 8888;

        // 创建TcpListener实例
        TcpListener listener = new TcpListener(ipAddress, port);

        Console.WriteLine($"服务器启动,等待连接: {ipAddress}:{port}");
        
        // 开始监听
        listener.Start();
        
        try
        {
            while (true)
            {
                // 等待客户端连接
                TcpClient client = listener.AcceptTcpClient();
                Console.WriteLine("客户端已连接");

                // 获取网络流,用于读取客户端发送的数据
                NetworkStream stream = client.GetStream();

                // 读取数据
                byte[] buffer = new byte[1024];
                int read = stream.Read(buffer, 0, buffer.Length);
                string dataReceived = Encoding.ASCII.GetString(buffer, 0, read);
                Console.WriteLine($"接收到的消息: {dataReceived}");

                // 发送响应
                string response = "你好,客户端!";
                byte[] sendData = Encoding.ASCII.GetBytes(response);
                stream.Write(sendData, 0, sendData.Length);

                // 关闭客户端连接
                client.Close();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
        finally
        {
            // 停止监听
            listener.Stop();
        }
    }

    public static void Main(string[] args)
    {
        StartServer();
    }
}


这些示例假设在同一台机器上运行服务端和客户端,因此使用了localhost(即127.0.0.1)作为IP地址。在实际应用中,服务端IP应为实际服务器的IP地址。
在实际部署时,确保防火墙配置允许相应的端口通信。
这些代码仅提供了基本功能,生产环境中可能需要更复杂的错误处理和性能优化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值