只有5个客户端的c#的网络编程
在C#中进行网络编程可以通过使用.NET Framework提供的Socket类来实现。以下是一个简单的例子,假设你要实现一个基于TCP协议的服务器和客户端,服务器只需支持5个客户端连接。
服务器端
服务器端代码如下:
csharpusing System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class Server
{
private TcpListener tcpListener;
private Thread listenThread;
private int clientCount = 0; // 记录客户端连接数
public Server()
{
this.tcpListener = new TcpListener(IPAddress.Any, 12345); // 监听本地IP地址的12345端口
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void ListenForClients()
{
this.tcpListener.Start();
while (clientCount < 5) // 只允许5个客户端连接
{
TcpClient client = this.tcpListener.AcceptTcpClient();
clientCount++;
Console.WriteLine($"Client {clientCount} connected.");
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while ((bytesRead = clientStream.Read(message, 0, 4096)) != 0)
{
// 处理客户端发送的数据,这里只是简单地输出到控制台
Console.WriteLine($"Received: {System.Text.Encoding.ASCII.GetString(message, 0, bytesRead)}");
clientStream.Write(message, 0, bytesRead);
}
tcpClient.Close();
}
public static void Main()
{
Server server = new Server();
}
}
客户端
客户端代码如下:
csharpusing System;
using System.Net.Sockets;
public class Client
{
public void Connect(string server, string message)
{
try
{
TcpClient client = new TcpClient(server, 12345);
byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
NetworkStream stream = client.GetStream();
stream.Write(data, 0, data.Length);
byte[] responseData = new byte[4096];
int bytesRead = stream.Read(responseData, 0, 4096);
string response = System.Text.Encoding.ASCII.GetString(responseData, 0, bytesRead);
Console.WriteLine("Received: " + response);
stream.Close();
client.Close();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
}
public static void Main()
{
Client client = new Client();
client.Connect("127.0.0.1", "Hello from client!");
}
}
说明
服务器端:使用TcpListener监听端口,通过AcceptTcpClient()接受客户端连接。在ListenForClients()方法中,通过while循环控制最多允许5个客户端连接,并为每个连接创建一个新的线程来处理通信。
客户端:使用TcpClient连接服务器,发送数据并接收响应。Connect()方法中,创建一个TcpClient实例连接到指定的服务器地址和端口。
关键字
C#, .NET Framework, Socket, TcpListener, TcpClient, NetworkStream, 多线程