C#中 用socket实现多个个客户端的相互聊天功能
时间: 2023-08-21 15:01:50 浏览: 173
好的,下面是一个简单的 C# socket 多客户端聊天示例代码,其中使用了 TCP 协议。
服务端代码:
```csharp
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace SocketServer
{
class Program
{
static List<TcpClient> clientsList = new List<TcpClient>();
static void Main(string[] args)
{
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 1234);
TcpListener listener = new TcpListener(localEndPoint);
listener.Start();
Console.WriteLine("Server started, waiting for client to connect...");
while (true)
{
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("Client connected: " + client.Client.RemoteEndPoint.ToString());
clientsList.Add(client);
BroadcastMessage(client.Client.RemoteEndPoint.ToString() + " joined the chat");
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024];
while (true)
{
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string message = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received message: " + message);
if (message == "quit")
{
clientsList.Remove(client);
BroadcastMessage(client.Client.RemoteEndPoint.ToString() + " left the chat");
break;
}
BroadcastMessage(client.Client.RemoteEndPoint.ToString() + ": " + message);
}
stream.Close();
client.Close();
}
listener.Stop();
}
static void BroadcastMessage(string message)
{
byte[] buffer = Encoding.ASCII.GetBytes(message);
foreach (TcpClient client in clientsList)
{
NetworkStream stream = client.GetStream();
stream.Write(buffer, 0, buffer.Length);
}
}
}
}
```
客户端代码:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace SocketClient
{
class Program
{
static void Main(string[] args)
{
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234);
TcpClient client = new TcpClient();
client.Connect(remoteEndPoint);
Console.WriteLine("Connected to server: " + client.Client.RemoteEndPoint.ToString());
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024];
Thread receiveThread = new Thread(new ThreadStart(() =>
{
while (true)
{
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string message = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received message: " + message);
}
}));
receiveThread.Start();
while (true)
{
Console.Write("Enter your message: ");
string message = Console.ReadLine();
byte[] messageBuffer = Encoding.ASCII.GetBytes(message);
stream.Write(messageBuffer, 0, messageBuffer.Length);
if (message == "quit")
break;
}
stream.Close();
client.Close();
}
}
}
```
以上代码演示了一个简单的 TCP socket 多客户端聊天程序,服务端可以接受多个客户端连接,每个客户端之间可以相互发送消息,客户端程序可以通过控制台进行输入和输出。
阅读全文