要在C#中實現一個基于TCP/IP的聊天室,你需要創建一個服務器端和客戶端
首先,創建一個新的C#控制臺應用程序項目,命名為"ChatServer"。
在項目中添加以下命名空間:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
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);
}
}
}
}
保存并運行ChatServer項目。服務器將開始監聽端口8000。
創建一個新的C#控制臺應用程序項目,命名為"ChatClient"。
在項目中添加以下命名空間:
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
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);
}
}
}
這個示例展示了如何使用C#創建一個基本的TCP/IP聊天室。你可以根據需要對其進行擴展和優化。