0
点赞
收藏
分享

微信扫一扫

使用C#实现交互式TCP服务器通信:实现对话功能及退出机制

进击的包籽 04-21 14:30 阅读 1

一、服务器端

using System.Net;
using System.Net.Sockets;
using System.Text;
TcpListener server = new TcpListener(IPAddress.Any, 9999);
server.Start();
Console.WriteLine("服务已开启");
while (true)
{
    TcpClient client = server.AcceptTcpClient();
    Thread thread = new Thread(HandleCilent);
    thread.Start(client);
}
static void HandleCilent(object obj)
{
    TcpClient client = (TcpClient)obj;
    NetworkStream stream = client.GetStream();
    byte[] data = new byte[1024];
    int byteRead;
    try
    {
        while ((byteRead = stream.Read(data, 0, data.Length)) != 0)
        {
            string message = Encoding.UTF8.GetString(data, 0, byteRead);
            Console.WriteLine("接收到" + message);
            byte[] response = Encoding.UTF8.GetBytes("服务器接收到" + message);
            stream.Write(response, 0, response.Length);
        }

    }
    catch (IOException ex)
    {
        Console.WriteLine("客户端已断开"+ex.ToString());
    }
    finally {
        client.Close();
    }
   
}

二、客户端

public class Program
{
    static void Main(string[] args)
    {
        TcpClient client = new TcpClient("8.130.127.7", 9999);
        NetworkStream stream = client.GetStream();

        while (true)
        {
            Console.WriteLine("请输入要发送的消息(输入 'exit' 退出):");
            string message = Console.ReadLine();

            if (message.ToLower() == "exit")
            {
                break;
            }

            byte[] data = Encoding.UTF8.GetBytes(message);
            stream.Write(data, 0, data.Length);

            // 接收服务器的响应
            byte[] responseData = new byte[1024];
            int bytesRead = stream.Read(responseData, 0, responseData.Length);
            string response = Encoding.UTF8.GetString(responseData, 0, bytesRead);
            Console.WriteLine("服务器消息:" + response);
        }

        client.Close();

    }
}
举报

相关推荐

0 条评论