我的多线程服务器上有一个名为 Clients 的类。
我的问题是如何从另一个类向指定的客户端发送数据? 这是我在 ServerMain 类中的监听函数。
public static List<Client> clients;
public static List<Thread> threads;
private void Listen()
{
clients = new List<Client>();
threads = new List<Thread>();
int id = 0;
while (true)
{
listenerSocket.Listen(0);
Log.Status(" Waiting for a connection...");
var commands = new ServerCommands();
//commands.Wait();
Client c1 = new Client(id, listenerSocket.Accept());
clients.Add(c1);
Log.Status("New Client Connected!");
Thread t = new Thread(c1.Start);
c1.SetThread = t;
t.Start();
id++;
}
}
我的客户端类只有一个发送示例
public class Client : IDisposable
{
public int _id;
public string _guid;
public string Name;
public Socket clientSocket;
private Thread thread;
public Client(int id, Socket socket)
{
this._id = id;
this._guid = Guid.NewGuid().ToString();
this.clientSocket = socket;
}
public Thread SetThread
{
set
{
this.thread = value;
}
}
public int Id
{
get
{
return this._id;
}
}
public void Receive()
{
byte[] buffer;
int readBytes;
while (clientSocket != null && clientSocket.Connected)
{
try
{
buffer = new byte[clientSocket.SendBufferSize];
readBytes = clientSocket.Receive(buffer);
if (readBytes > 0)
{
Packet p = new Packet(buffer);
if (p.Type != PacketType.Disconnect)
{
new Task(() => Received(p)).Start();
}
else
{
CloseConnection();
}
}
}
catch (SocketException e)
{
Console.WriteLine(e);
CloseConnection();
}
}
}
////////// Example Send Function ////////////
private void Register(User user)
{
var res = Handler.RegisterDo(user);
clientSocket.Send(res.ToBytes());
}
}
我知道我可以像这样发送给所有连接的客户端
foreach(Client item in ServerMain.clients) //Client clients
{
Console.WriteLine(item._id);
Console.WriteLine(item.Name);
Console.WriteLine(item._guid);
};
我是否缺少一些需要识别的东西? id 可以做到(我认为),但是我如何从外部调用它?
根据我对代码的理解,您只需将
'client'
连接套接字包装为类客户端。您只需将客户端类的 'this.clientSocket'
字段调用为 send()
或 receive()
数据即可。