91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

C#實現基于TCP/IP的聊天室

c#
小樊
81
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
永兴县| 芜湖市| 广州市| 龙江县| 涡阳县| 古丈县| 韶关市| 栖霞市| 汶上县| 枞阳县| 伊宁市| 花莲县| 潮州市| 临西县| 凌海市| 枞阳县| 浦江县| 南皮县| 富川| 法库县| 侯马市| 安化县| 华坪县| 乌鲁木齐县| 西昌市| 九寨沟县| 阜新| 纳雍县| 永胜县| 三亚市| 永和县| 买车| 屏东县| 安岳县| 班玛县| 乐山市| 阳谷县| 垦利县| 定日县| 诸城市| 岑巩县|