C#中 用socket实现多个个客户端的相互聊天功能
时间: 2023-08-21 17:01:50 浏览: 102
C#Socket网络通信实现多人聊天
实现多个客户端的相互聊天功能,可以采用C#中的Socket编程来实现,以下是一个简单的示例代码:
服务端代码:
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Server
{
class Program
{
private static Socket serverSocket;
private static byte[] buffer = new byte[1024];
private static List<Socket> clientSockets = new List<Socket>();
static void Main(string[] args)
{
Console.WriteLine("Starting server...");
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8080));
serverSocket.Listen(5);
Console.WriteLine("Server started on port 8080");
while (true)
{
Socket clientSocket = serverSocket.Accept();
clientSockets.Add(clientSocket);
Console.WriteLine($"Client connected: {clientSocket.RemoteEndPoint}");
Thread thread = new Thread(() => ListenClient(clientSocket));
thread.Start();
}
}
private static void ListenClient(Socket clientSocket)
{
while (true)
{
int bytesReceived = clientSocket.Receive(buffer);
if (bytesReceived == 0)
{
clientSockets.Remove(clientSocket);
Console.WriteLine($"Client disconnected: {clientSocket.RemoteEndPoint}");
break;
}
string message = Encoding.ASCII.GetString(buffer, 0, bytesReceived);
Console.WriteLine($"Received message '{message}' from client {clientSocket.RemoteEndPoint}");
foreach (Socket socket in clientSockets)
{
if (socket != clientSocket)
{
socket.Send(Encoding.ASCII.GetBytes(message));
}
}
}
}
}
}
```
客户端代码:
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace Client
{
class Program
{
private static Socket clientSocket;
private static byte[] buffer = new byte[1024];
static void Main(string[] args)
{
Console.WriteLine("Connecting to server...");
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080));
Console.WriteLine("Connected to server");
while (true)
{
Console.Write("Enter message: ");
string message = Console.ReadLine();
clientSocket.Send(Encoding.ASCII.GetBytes(message));
int bytesReceived = clientSocket.Receive(buffer);
string receivedMessage = Encoding.ASCII.GetString(buffer, 0, bytesReceived);
Console.WriteLine($"Received message from server: {receivedMessage}");
}
}
}
}
```
这里是一个简单的示例,客户端和服务端都是单线程运行的,无法处理并发连接,需要根据实际需求进行改进。
阅读全文