coder-client/src/com/coder/client/CoderClient.java

100 lines
2.5 KiB
Java
Raw Normal View History

2015-10-09 13:37:45 +00:00
package com.coder.client;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
2015-10-09 13:37:45 +00:00
import com.coder.client.LoginDialog.LoginDialogAction;
import com.coder.server.CoderServer;
import zutil.log.LogUtil;
public class CoderClient extends Thread{
public static final Logger logger = LogUtil.getLogger();
private String url;
private int port;
private Session session;
private ClientWindow window;
private LoginDialog loginDialog;
2015-10-09 13:37:45 +00:00
public CoderClient(String url, int port) {
this.url = url;
this.port = port;
this.window = new ClientWindow("CoderClient");
2015-10-09 13:37:45 +00:00
super.start();
}
public void run(){
//save the previously typed user name
2015-10-09 13:37:45 +00:00
String username = "";
while(true){
//close previou session if applicable
closeCurrentSession();
//setup a new session
2015-10-09 13:37:45 +00:00
this.session = Session.setupConnection(url, port);
if(session == null){
logger.info("Could not setup a connection to " + url + ":" + port);
continue;
}
//ask for username and passwor din a dialog window
2015-10-09 13:37:45 +00:00
LoginDialog loginDialog = new LoginDialog(username, null);
loginDialog.setVisible(true); //blocking
loginDialog.dispose();
2015-10-09 13:37:45 +00:00
if(loginDialog.getAction() == LoginDialogAction.CANCEL){
logger.info("Login dialog closed or canceled by the user. terminating.");
break;
}
//authenticate the user
2015-10-09 13:37:45 +00:00
username = loginDialog.getUsername();
String password = new String(loginDialog.getPassword());
2015-10-09 13:37:45 +00:00
boolean authenticated = session.authenticate(username, password);
if(!authenticated){
JOptionPane.showMessageDialog(null, "Wrong username or password", "Authentication Failed", JOptionPane.INFORMATION_MESSAGE);
2015-10-09 13:37:45 +00:00
System.out.println("Authentication failed");
continue;
}
//start receiving traffic from the server
2015-10-09 13:37:45 +00:00
session.start();
//show the user the main GUI
2015-10-09 13:37:45 +00:00
this.window.setVisible(true);
try {Thread.sleep(1000);} catch (InterruptedException e) {}
//wait here until the session is closed for some reason
2015-10-09 13:37:45 +00:00
while(session.isConnected()){
Thread.yield();
}
//hide the main GUI
2015-10-09 13:37:45 +00:00
logger.info("The socket was closed. terminating.");
this.window.setVisible(false);
Thread.yield();
}
closeCurrentSession();
this.window.dispose();
2015-10-09 13:37:45 +00:00
System.exit(0);
}
private void closeCurrentSession(){
if(this.session != null){
session.close();
session = null;
}
}
2015-10-09 13:37:45 +00:00
public static void main(String[] args){
int port = CoderServer.SERVER_PORT;
new CoderClient("127.0.0.1", port);
}
}