Skip to main content

Socket communication between server and client using threads [closed]



I am busy with a project where the client Gui sends user and password details to a server where the details needs to be verified Sever side against the data in the database on the server. We are required to use Threads(from what I understand is that the Server needs to be able to handle multiple requests).





Where I get stuck is when the server is started it is set so that is can listen to requests from clients. However the Server gets stuck listening to client requests until it received a request from the client.





Furthermore on the client side if I send wrong username and password I struggle to re-submit the info for verification.





This is the code that I have used. Would just like to know if I am on the right track?





Firstly I start the server.







private void butStartUpServerActionPerformed(java.awt.event.ActionEvent evt) {



try

{



Class.forName(driverName);



connection = DriverManager.getConnection(SourceURL);



Statement verifyUsernamePassword = connection.createStatement();



user = txtUsernameServer.getText();



passwordChar = txtPasswordServer.getPassword();



password = new String(passwordChar);





//now I execute query using a statement object

ResultSet checkUsernamePassword = verifyUsernamePassword.executeQuery("SELECT * FROM User WHERE userName = '" + user + "' AND password = '" + password + "'");



//if cursor does move to next row indicating that a record has been found

if(checkUsernamePassword.next())

{

JOptionPane.showMessageDialog(null, "The server has been started successfully");

//starting up a server socket connection

ServerSoc = new ServerSocket(7777);



listening = true;



butShutDownServer.setEnabled(true);



butStartUpServer.setEnabled(false);



while(listening)

{

boolean verifyAdministratorDetails = false;





clientSocket = ServerSoc.accept();





in = new DataInputStream(clientSocket.getInputStream());



BufferedReader is = new BufferedReader(new InputStreamReader(in));



os = new PrintStream(clientSocket.getOutputStream());



String AdministratorDetails = is.readLine();

boolean adminBoolenDetails = Boolean.parseBoolean(AdministratorDetails);

if(adminBoolenDetails == true)

{

//I userNameAdminLogin from client side

String userNameAdminLogin = is.readLine();

//I userNameAdminLogin from client side

String passwordAdminLogin = is.readLine();

//Now I check if the details exist in the database

Statement statementVerifyAdminDetailsClientSide = connection.createStatement();



ResultSet verifyAdminDetailsClientSide = statementVerifyAdminDetailsClientSide.executeQuery("SELECT * FROM User WHERE userName = '" + userNameAdminLogin + "' AND password = '" + passwordAdminLogin + "'");



boolean verificationSuccess;

if(verifyAdminDetailsClientSide.next())

{

verificationSuccess = true;

listening = false;



}

else

{

verificationSuccess = false;

listening = true;

}

os.println(verificationSuccess);







}







}



}

else

{

JOptionPane.showMessageDialog(null, "Please enter correct user name and password to start up server (check spelling)");

}







Now I run the client. Constructor.







public class Administrator extends javax.swing.JFrame implements Runnable







{ Socket clientSocket = null; PrintWriter out = null; BufferedReader in; Thread runner;







public Administrator()

{

super("Administrator Window");

initComponents();

try

{

//I call the socket constructor

clientSocket = new Socket("192.168.56.1", 7777);





}

catch(UnknownHostException uh){}

catch(IOException io)

{

JOptionPane.showMessageDialog(null, io.toString());

}

catch(NullPointerException nullpoint)

{

JOptionPane.showMessageDialog(null, nullpoint.toString());

}

}







I run the thread in the button eventhandler...is that right?







private void butSubmitActionPerformed(java.awt.event.ActionEvent evt) {



//I open InputStream and OutputStream

try

{

in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

out = new PrintWriter(clientSocket.getOutputStream(), true);



}

catch(IOException io)

{

JOptionPane.showMessageDialog(null, io.toString());

}





//now i start my thread

//starting the thread

while(runner == null)

{

runner = new Thread(this);

//the run method will now be executed throught the start method

runner.start();

}

}

public void run()

{

boolean verifyAdministratorDetails;

String userNameAdminLogin;

String passwordAdminLogin;

while(runner == Thread.currentThread())

{

userNameAdminLogin = txtUserName.getText();

passwordAdminLogin = txtPassword.getText();

verifyAdministratorDetails = true;

out.println(verifyAdministratorDetails);

out.println(userNameAdminLogin);

out.println(passwordAdminLogin);





try

{

String verifcationSuccess = in.readLine();





if(verifcationSuccess.equals("true"))

{

JOptionPane.showMessageDialog(null, "Login Successfull");



}

else

{

JOptionPane.showMessageDialog(null, "Please enter correct user name and password (check spelling)");



}



System.out.println(verifcationSuccess);



}

catch(IOException io)

{

JOptionPane.showMessageDialog(null, io.toString());

}



}



}







Regards Arian


Comments

  1. It looks like your server is started from a Button press or similar, since you have an ActionEvent in the method. Your server doesn't currently start a new Thread to handle requests. The result of this is that your server GUI will probably lock up as soon as you start the server.

    (Java GUIs use a dedicated thread called the Event Dispatching Thread (EDT), often called the AWT Thread or the Swing Thread - if you perform long-running tasks on this thread then the GUI will stop responding).

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.