温馨提示×

C#实现基于TCP/IP的聊天室

c#
小樊
83
2024-09-14 23:41:30
栏目: 编程语言

要在C#中实现一个基于TCP/IP的聊天室,你需要创建一个服务器端和客户端

  1. 首先,创建一个新的C#控制台应用程序项目,命名为"ChatServer"。

  2. 在项目中添加以下命名空间:

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
  1. 在Program类中添加以下代码:
class Program
{
    private static TcpListener _listener;
    private static List<TcpClient> _clients = new List<TcpClient>();

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

    private static void StartServer()
    {
        _listener = new TcpListener(IPAddress.Any, 8000);
        _listener.Start();
        Console.WriteLine("服务器已启动,正在监听端口8000...");

        while (true)
        {
            TcpClient client = _listener.AcceptTcpClient();
            _clients.Add(client);
            Console.WriteLine($"客户端 {client.Client.RemoteEndPoint} 已连接");

            Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClient));
            clientThread.Start(client);
        }
    }

    private static void HandleClient(object obj)
    {
        TcpClient client = (TcpClient)obj;
        NetworkStream stream = client.GetStream();

        while (true)
        {
            try
            {
                byte[] buffer = new byte[1024];
                int bytesRead = stream.Read(buffer, 0, buffer.Length);
                string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);

                if (message == "exit")
                {
                    _clients.Remove(client);
                    client.Close();
                    Console.WriteLine($"客户端 {client.Client.RemoteEndPoint} 已断开连接");
                    break;
                }

                BroadcastMessage(client, message);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"客户端 {client.Client.RemoteEndPoint} 发生错误: {ex.Message}");
                _clients.Remove(client);
                client.Close();
                break;
            }
        }
    }

    private static void BroadcastMessage(TcpClient sender, string message)
    {
        foreach (TcpClient client in _clients)
        {
            if (client != sender)
            {
                NetworkStream stream = client.GetStream();
                byte[] buffer = Encoding.UTF8.GetBytes(message);
                stream.Write(buffer, 0, buffer.Length);
            }
        }
    }
}
  1. 保存并运行ChatServer项目。服务器将开始监听端口8000。

  2. 创建一个新的C#控制台应用程序项目,命名为"ChatClient"。

  3. 在项目中添加以下命名空间:

using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
  1. 在Program类中添加以下代码:
class Program
{
    private static TcpClient _client;
    private static NetworkStream _stream;

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

    private static void ConnectToServer()
    {
        _client = new TcpClient("127.0.0.1", 8000);
        _stream = _client.GetStream();
        Console.WriteLine("已连接到服务器");

        Thread receiveThread = new Thread(ReceiveMessages);
        receiveThread.Start();

        SendMessages();
    }

    private static void ReceiveMessages()
    {
        while (true)
        {
            try
            {
                byte[] buffer = new byte[1024];
                int bytesRead = _stream.Read(buffer, 0, buffer.Length);
                string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                Console.WriteLine(message);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生错误: {ex.Message}");
                _client.Close();
                break;
            }
        }
    }

    private static void SendMessages()
    {
        while (true)
        {
            Console.Write("请输入消息: ");
            string message = Console.ReadLine();

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

            byte[] buffer = Encoding.UTF8.GetBytes(message);
            _stream.Write(buffer, 0, buffer.Length);
        }
    }
}
  1. 保存并运行ChatClient项目。多个客户端可以同时连接到服务器并发送消息。

这个示例展示了如何使用C#创建一个基本的TCP/IP聊天室。你可以根据需要对其进行扩展和优化。

0