Sorting Sockets as Client Objects

心不动则不痛 提交于 2019-12-24 13:09:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!