Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.IOException;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- 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 {
- ChatMessage cm2 = null;
- outStream = new ObjectOutputStream(socket.getOutputStream());
- inStream = new ObjectInputStream(socket.getInputStream());
- while(true){
- try{
- cm2 = (ChatMessage)(inStream.readObject());
- }catch(ClassNotFoundException cnf){
- System.out.println(cnf);
- }
- int type = cm2.getType();
- if(type==3){
- if(loginAttempt(cm2.getMessage())){
- writeMsg(3, "true");
- break;
- }else{
- writeMsg(3, "false");
- }
- } else if(type==4){
- if(register(cm2.getMessage())){
- writeMsg(4, "true");
- }else{
- writeMsg(4, "false");
- }
- }
- }
- String[] messages = cm2.getMessage().split("\\$");
- username = messages[0];
- System.out.println(username + " connected");
- broadcast(username + " has connected.");
- } catch (IOException e) {
- System.out.println("Exception creating streams");
- return;
- }
- }
- public void run() {
- // to loop until LOGOUT
- boolean running = true;
- WhoIsIn();
- 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);
- System.out.println(username + " closed connection.");
- break;
- }
- catch(ClassNotFoundException e2) {
- break;
- }
- String message = cm.getMessage();
- // Switch on the type of message receive
- switch(cm.getType()) {
- case ChatMessage.MESSAGE:
- System.out.println(message);
- broadcast(username + ": " + message);
- break;
- case ChatMessage.LOGOUT:
- System.out.println(username + " disconnected with a LOGOUT message.");
- running = false;
- remove(id);
- 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(3, "true");
- }else{
- writeMsg(3, "false");
- }
- break;
- case ChatMessage.REGISTER:
- if(register(message)){
- writeMsg(4, "true");
- // loginAttempt(message); auto login if register is successful?
- } else{
- writeMsg(4, "false");
- }
- break;
- case ChatMessage.PRIVATE:
- System.out.println("private message:");
- String userName = "", messagepm = "";
- try{
- String[] messages = message.split("\\:", 2);
- userName = messages[0];
- messagepm = messages[1];
- System.out.println(userName);
- System.out.println(messagepm);
- }catch(Exception e){
- System.out.println(e);
- writeMsg(5, "false");
- break;
- }
- try{
- messagepm = (time.format(new Date())) + " from:" + userName + " ~ " + messagepm + "\n"; // add HH:mm:ss and \n to the message
- for(int i = clientList.size(); --i >= 0;) {
- ClientThread ct = clientList.get(i);
- if(ct.username.equals(userName)){
- // try to write to the Client if it fails remove it from the list
- if(!ct.writeMsg(5, messagepm)) {
- clientList.remove(i);
- System.out.print("Disconnected Client " + ct.username + " removed from list.");
- writeMsg(5, "false2");
- }else{
- writeMsg(5, "true");
- }
- }
- }
- }catch(Exception e){
- System.out.println("Private message error\\!" + e);
- }
- 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 boolean writeMsg(int type ,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 {
- ChatMessage LogObj = new ChatMessage(type, msg);
- outStream.writeObject(LogObj);
- }
- 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(1, 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 = "";
- try{
- password = messages[1];
- }catch(ArrayIndexOutOfBoundsException arrayofb){
- System.out.println("no password");
- }
- 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 = "";
- while(rs.next()){
- storedPassword = rs.getString(storedPassword + "PASSWORD");
- }
- if(BCrypt.checkpw(password, storedPassword)){
- return true;
- }
- return false;
- }catch(ClassNotFoundException | SQLException e){
- e.printStackTrace();
- System.out.println("999");
- return false;
- }catch(Exception ee){
- System.out.println("login failed.");
- return false;
- }
- finally{
- try{
- st.close();
- conn.close();
- }catch(SQLException e){
- e.printStackTrace();
- }
- }
- }
- private synchronized boolean register(String message){
- String[] messages = message.split("\\$");
- String username = messages[0];
- String password = "";
- try{
- password = messages[1];
- }catch(ArrayIndexOutOfBoundsException arrayofb){
- System.out.println("no password (Register)");
- }
- System.out.println("Creating account, " + username + "\npassword:"+ password);
- 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();
- try{
- hashed = BCrypt.hashpw(password, BCrypt.gensalt());
- st.executeUpdate("insert into users values('" + username + "', '" + hashed + "');");
- System.out.println("Registration successful");
- return true;
- }catch(Exception sqle){
- System.out.println("Registration failed");
- return false;
- }
- }catch(ClassNotFoundException | SQLException e){
- e.printStackTrace();
- }finally{
- try{
- st.close();
- conn.close();
- }catch(SQLException e){
- e.printStackTrace();
- }
- }
- return false;
- }
- private synchronized void WhoIsIn(){
- for(int i = clientList.size(); --i >= 0;) {
- try{
- ClientThread ct = clientList.get(i);
- ct.writeMsg(0, "#");
- // try to write to the Client if it fails remove it from the list
- for(int x = clientList.size(); --i >= 0;){
- ClientThread ctx = clientList.get(x);
- ct.writeMsg(0, ctx.username);
- }
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- }
- 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) {
- broadcast(ct.username +" has disconnected.");
- clientList.remove(i);
- WhoIsIn();
- return;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement