I am new to socket programming. I am developing a multiple client -server system. In that the clients need to register their credentials when they are sending connection request to the server. The server will authenticate it.
I have read some tutorials on client server programming. I understood how the sockets work. But my question is what should I do for this registration and authentication? Can I just send a username pwd as message in the output stream? Or is there any other better way to achieve this ?
Please guide me how do I achieve this ?
You can do this in a similar manner as web server do, by maintaining a session. Here goes the steps.
Client Code:
Class Client
{
private String uname;
private String password;
private String session;
public String[2] message;
//getter setter
}
//Inside Main Class
int sendInfo(String mesg)
{
Client c=getClient(); //this function gives your Client Object with either session and username password etc preset,
if(c.getSession()!==null || !c.getSession()!="")
{
c.message[0]=c.getSession(); //first String contains your session
c.message[1]=mesg; //next string contains your message
}
else
{
c.message[0]=c.getUsername+"|"+c.getPassword(); //first String contains your session
c.message[1]=mesg; //next string contains your message
}
sendMessageToServer(c.message);
}
Server Code
Class Server
{
private List<String> activeSession();
//getter setter
void addActiveSession(String session)
{
this.activeSession.add(session);
}
String generateSession(String uname,String password)
{
String sessionHash="RemoteSession"+this.activeSession.size()+uname+password;
return sessionHash;
}
void serverReceive()
{
//Logic for listener
String msg[]=getClientMessage();
if(msg[0].indexOf('|')<0)
{
//it contains session. Check in activeSesion list
}
else
{
//It cotains username & password separeted by |. Call Authenticate
String
}
}
void authenticateConnection(String username,String pass)
{
if(checkUnameandPassword(username,pass))
{
//if the uname and pass is valid
this.addActiveSession(generateSession(username,password))
}
else
{
sendConnectionrefuse();
}
}
}
Hope this will help you
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments