问题
I'm currently making chat program in C#, and I have a question regarding connection of clients.
How can I make each client (socket) that connects to the server have a name and more details?
For example:
Joe connects to server. A new object, c1, is created containing his name and IP (for kicking/muting/private messaging purposes).
Later, James connects to server. A new object, c2 is created containing the name and IP of James.
And so on...
I need to make the clients as objects for few main purposes.
As an example, if I want to kick someone from the chat, I can write in the server "/kick " and it'll kick him.
I want the server to check for a client with that name. If its connected, kick it.
The only way to do it is to make an object for each client for these exact purposes.
So how can I make an object for each socket?
回答1:
Just wrap all related information in a class:
class ClientInfo {
public string Name { get; set; }
public Socket Socket { get; set; }
}
You just need a single list of those:
List<ClientInfo> clients = new List<ClientInfo>();
You can easily add a client when one has connected:
clients.Add(new ClientInfo() { Name = "x", Socket = someSocket });
You can also find clients by Name and by Socket:
var client = clients.SingleOrDefault(x => x.Name == "x");
client.Socket.Send(...);
回答2:
What you could do is when a client connects to your server, you have the clients send your server whom they are (assuming you don't have any security). Then you could create an object that wraps the new incoming socket connections. Using this page http://msdn.microsoft.com/en-us/library/fx6588te(v=vs.110).aspx you could implement your logic in the AcceptCallback method to get the socket that's connected and put it in an object. I hope I understood your question correctly!
来源:https://stackoverflow.com/questions/20846419/sorting-sockets-as-client-objects