Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package chatServer;
- import java.io.*;
- import java.sql.*;
- import java.net.*;
- import java.text.SimpleDateFormat;
- import java.util.*;
- import java.util.Date;
- import org.mindrot.jbcrypt.BCrypt;
- public class Server {
- private static int clientId;
- private ArrayList<ClientThread> clientList;
- private SimpleDateFormat time;
- private int port;
- private boolean running;
- public static void main(String[] args) {
- // start server on port 9007 unless a PortNumber is specified
- int portNumber = 9007;
- switch(args.length) {
- case 1:
- try {
- portNumber = Integer.parseInt(args[0]);
- }
- catch(Exception e) {
- System.out.println("Invalid port number.");
- System.out.println("Java Server [portNumber]");
- return;
- }
- case 0:
- break;
- default:
- System.out.println("Java Server [portNumber]");
- return;
- }
- // create a server object and start it
- Server server = new Server(portNumber);
- server.start();
- }
- public Server(int port){
- this.port = port;
- time = new SimpleDateFormat("HH:mm:ss");
- clientList = new ArrayList<ClientThread>();
- Statement st = null;
- Connection conn = null;
- try{
- Class.forName("org.h2.Driver");
- conn = DriverManager.getConnection("jdbc:h2:~/messageserver", "server", "server");
- st = conn.createStatement();
- st.execute("create table if not exists users(UserName varchar(20) primary key, Password varchar(255));");
- }catch(ClassNotFoundException | SQLException e){
- e.printStackTrace();
- }finally{
- try{
- st.close();
- conn.close();
- }catch(SQLException e){
- e.printStackTrace();
- }
- }
- }
- public void start(){
- running = true;
- try {
- ServerSocket serverSocket = new ServerSocket(port);
- while(running)
- {
- System.out.println("Waiting for connections. Port = " + port);
- Socket socket = serverSocket.accept();
- if(!running)
- break;
- ClientThread t = new ClientThread(socket);
- clientList.add(t); // Needs changing for registered users
- t.start();
- }
- try {
- serverSocket.close();
- for (int i = 0; i < clientList.size(); i++)
- {
- ClientThread tc = clientList.get(i);
- try {
- tc.inStream.close();
- tc.outStream.close();
- tc.socket.close();
- } catch (IOException e) {
- }
- }
- } catch (Exception e) {
- System.out.println("Problem closing connections and server" + e);
- }
- } catch (IOException e){
- String msg = time.format(new Date()) + " Exception on ServerSocket: " + e + "\n";
- System.out.println(msg);
- }
- }
- protected void stop() {
- running = false;
- try {
- new Socket("localhost", port);
- } catch (Exception e) {
- }
- }
- public class ClientThread extends Thread {
- Socket socket;
- ObjectInputStream inStream;
- ObjectOutputStream outStream;
- String date;
- int id;
- public String username;
- ChatMessage cm;
- ClientThread(Socket socket){
- this.socket = socket;
- id = ++clientId;
- try {
- outStream = new ObjectOutputStream(socket.getOutputStream());
- inStream = new ObjectInputStream(socket.getInputStream());
- username = (String) inStream.readObject();
- System.out.print(username + " connected");
- } catch (IOException e) {
- System.out.println("Exception creating streams");
- return;
- }
- catch (ClassNotFoundException e ) {
- }
- }
- public void run() {
- // to loop until LOGOUT
- boolean running = true;
- while(running) {
- // read a String (which is an object)
- try {
- cm = (ChatMessage) inStream.readObject();
- }
- catch (IOException e) {
- System.out.println(username + " Exception reading Streams: " + e);
- break;
- }
- catch(ClassNotFoundException e2) {
- break;
- }
- String message = cm.getMessage();
- // Switch on the type of message receive
- switch(cm.getType()) {
- case ChatMessage.MESSAGE:
- broadcast(username + ": " + message);
- break;
- case ChatMessage.LOGOUT:
- System.out.println(username + " disconnected with a LOGOUT message.");
- running = false;
- break;
- case ChatMessage.WHOISIN:
- writeMsg("List of the users connected at " + time.format(new Date()) + "\n");
- // scan al the users connected
- for(int i = 0; i < clientList.size(); ++i) {
- ClientThread ct = clientList.get(i);
- writeMsg((i+1) + ") " + ct.username + " since " + ct.date);
- }
- break;
- case ChatMessage.LOGIN:
- if(loginAttempt(message)){
- writeMsg("true");
- }else{
- writeMsg("false");
- }
- break;
- case ChatMessage.REGISTER:
- if(register(message)){
- writeMsg("true");
- // loginAttempt(message); auto login if register is successful?
- }
- break;
- }
- }
- remove(id);
- close();
- }
- private void close() {
- // try to close the connection
- try {
- if(outStream != null) outStream.close();
- }
- catch(Exception e) {}
- try {
- if(inStream != null) inStream.close();
- }
- catch(Exception e) {};
- try {
- if(socket != null) socket.close();
- }
- catch (Exception e) {}
- }
- private boolean writeMsg(String msg) {
- // if Client is still connected send the message to it
- if(!socket.isConnected()) {
- close();
- return false;
- }
- // write the message to the stream
- try {
- outStream.writeObject(msg);
- }
- catch(IOException e) {
- System.out.print("Error sending message to " + username);
- System.out.println(e.toString());
- }
- return true;
- }
- }
- private synchronized void broadcast(String message) {
- String currentTime = time.format(new Date());
- String messageLf = currentTime + " " + message + "\n"; // add HH:mm:ss and \n to the message
- System.out.print(messageLf);
- for(int i = clientList.size(); --i >= 0;) {
- ClientThread ct = clientList.get(i);
- // try to write to the Client if it fails remove it from the list
- if(!ct.writeMsg(messageLf)) {
- clientList.remove(i);
- System.out.print("Disconnected Client " + ct.username + " removed from list.");
- }
- }
- }
- private synchronized boolean loginAttempt(String message){
- String[] messages = message.split("$");
- String Lusername = messages[0];
- String password = messages[1];
- Statement st = null;
- Connection conn = null;
- try{
- String hashed = "";
- Class.forName("org.h2.Driver");
- conn = DriverManager.getConnection("jdbc:h2:~/messageserver", "server", "server");
- st = conn.createStatement();
- ResultSet rs = st.executeQuery("select password from users where username='" + Lusername + "';");
- String storedPassword = rs.getString("password");
- if(BCrypt.checkpw(password, storedPassword)){
- //ClientThread name = new ClientThread(socket)
- //username = Lusername; Need to update the username before returning true.
- return true;
- }
- return false;
- }catch(ClassNotFoundException | SQLException e){
- e.printStackTrace();
- }finally{
- try{
- st.close();
- conn.close();
- }catch(SQLException e){
- e.printStackTrace();
- }
- }
- return false;
- }
- private synchronized boolean register(String message){
- String[] messages = message.split("$");
- String username = messages[0];
- String password = messages[1];
- Statement st = null;
- Connection conn = null;
- try{
- String hashed = "";
- Class.forName("org.h2.Driver");
- conn = DriverManager.getConnection("jdbc:h2:~/messageserver", "server", "server");
- st = conn.createStatement();
- ResultSet rs = st.executeQuery("select username from users where username='" + username + "';");
- if(!rs.next()){
- hashed = BCrypt.hashpw(password, BCrypt.gensalt());
- st.executeUpdate("insert into users values('" + username + "', '" + hashed + "');");
- return true;
- }
- }catch(ClassNotFoundException | SQLException e){
- e.printStackTrace();
- }finally{
- try{
- st.close();
- conn.close();
- }catch(SQLException e){
- e.printStackTrace();
- }
- }
- return false;
- }
- synchronized void remove(int id) {
- // scan the array list until we found the Id
- for(int i = 0; i < clientList.size(); ++i) {
- ClientThread ct = clientList.get(i);
- // found it
- if(ct.id == id) {
- clientList.remove(i);
- return;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement