简体   繁体   中英

C# Multiple Client - Sending Nickname along with IP and port no

I am working on a C# multithreaded socket program. Client side code for connecting is:

 c.Connect(ipText.Text, port);  // Can I add nickName here? probably not?
 thrReceive = new Thread(new ThreadStart(Receive)); //Receive -> accepts buffers from server
 thrReceive.Start();

Before I start with the problem, a quick view of what I want to do: All data send by a client should be directed to all other clients but not the sender, so every time a client sends data, program should go over the list of clients and send the data.

What I am struggling with is along with port and IP, I want to send a nickname to the server. After that, server will check whether the nickname is unique. If not, it will reject the connection.

I thought of a trivial solution where client sends nickname with the sentence it sends, so this is after establishing connection with server. Server keeps a list of structs, lets say struct is called "param". "param" consists of 3 variables: 1)Socket 2)bool first = true 3)string nick

Whenever a new connection is established, a new "param" is created, initiating "first" to true and "nick" to empty string, and of course the socket to the client. And the very first time the same socket sends a data via a buffer, I will extract its nickname, set "first" to false and check its uniqueness, if not unique then disconnect the socket and delete the related entry.

I believe above solution is not a good solution, nothing near good actually:) There should be some proper way, I suppose.

You can not send data with the connection. That means you can not reject the connection but you can send packets for authenticating on the server. Example for that:

Client connects

Server accepts

Client sends something like "Auth [username]"

Server checks if username is free

If not: Server sends something like "RejectAuth" to the client and disconnects.

If it is free: Server sends something like "AcceptAuth" and the protocol continues (Sharing information, sending data, etc.)

Note: this is not the most optimal way. You could instead of disconnecting assign a random username and send him a change request. Thats much better because its faster and the user can send new usernames and instantly check if its free.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM