Site Loader

package ChatApplication;import java.io.*;import java.net.*;import java.text.SimpleDateFormat; // date format imported to keep track of chat import java.util.*;public class ServerClass {    private static int uID;    // array list there in order to the list of the people on the chat in the server window    private ArrayList employe;    // The following is the same as the above but made for the GUI     private ServerGUIclass serverGUI;    // will have the ability to have the date of the chat    private SimpleDateFormat date;    // connection number there so it the connection can be listend to    private int conNumb;    // the boolean that will be turned of to stop the server    private boolean Continue;    public ServerClass(int port) {        this(port, null);    }    public ServerClass(int port, ServerGUIclass sg) {        this.serverGUI = sg;        this.conNumb = port;        // this will display when the connection is establised        date = new SimpleDateFormat(“HH:mm:ss”);              employe = new ArrayList();    }    public void start() {        Continue = true;        //server is created via the socket, we now have to wait for connection        try {                        ServerSocket serverSocket = new ServerSocket(conNumb);            // loop created in order for a client connection             while (Continue) {                // while waiting for connection of employess, we can display the following message                 display(“Waiting for employee connection ” + conNumb + “.”);                Socket socket = serverSocket.accept();                // when asked to stop                if (!Continue) {                    break;                }                Employeeth t = new Employeeth(socket);                employe.add(t);                t.start();            }            // when asked to stop            try {                serverSocket.close();                for (int i = 0; i < employe.size(); ++i) {                    Employeeth tc = employe.get(i);                    try {                        tc.input.close();                        tc.output.close();                        tc.socket.close();                    } catch (IOException ioE) {                                            }                }            } catch (Exception e) {                display("Exception closing the server and clients: " + e);            }        }        catch (IOException e) {            String msg = date.format(new Date()) + " Exception on new ServerSocket: " + e + " ";            display(msg);        }    }    /*     * For the GUI to stop the server     */    protected void stop() {        Continue = false;        // connect to myself as Client to exit statement         // Socket socket = serverSocket.accept();        try {            new Socket("localhost", conNumb);        } catch (Exception e) {            // nothing I can really do        }    }    /* * Display an event (not a message) to the console or the GUI     */    private void display(String msg) {        String time = date.format(new Date()) + " " + msg;        if (serverGUI == null) {            System.out.println(time);        } else {            serverGUI.appendEvent(time + " ");        }    }    /* *  in order to send the same message to all employees      */    private synchronized void broadcast(String message) {        // date fromat before each message         String time = date.format(new Date());        String messageLf = time + " " + message + " ";        // in order to show message for GUI        if (serverGUI == null) {            System.out.print(messageLf);        } else {            serverGUI.appendRoom(messageLf);        }        // we loop in reverse order in case we would have to remove a Client        // because it has disconnected        for (int i = employe.size(); --i >= 0;) {            Employeeth ct = employe.get(i);            // try to write to the Client if it fails remove it from the list            if (!ct.writeMsg(messageLf)) {                employe.remove(i);                display(“Employee disconnected ” + ct.uName + ” has been taken of the list.”);            }        }    }    // when the employee wishes to logout of the chat    synchronized void remove(int id) {        // this will look through the array list created from the id and employee will be removed        for (int i = 0; i < employe.size(); ++i) {            Employeeth ct = employe.get(i);                        if (ct.id == id) {                employe.remove(i);                return;            }        }    }    public static void main(String args) {        //sever number 99 will be with the start up unless this is changed        int serverNumber = 99;        switch (args.length) {            case 1:                try {                    serverNumber = Integer.parseInt(args0);                } catch (Exception e) {                    System.out.println("Wrong Server Number, please try again.");                    System.out.println("Usage is: > java Server serverNumber”);                    return;                }            case 0:                break;            default:                System.out.println(“Usage is: > java Server serverNumber”);                return;        }        // create a server object and start it        ServerClass server = new ServerClass(serverNumber);        server.start();    }       class Employeeth extends Thread {        // where we will listen and talk        Socket socket;        ObjectInputStream input;        ObjectOutputStream output;        // my unique id (easier for deconnection)        int id;        // the Username of the Client        String uName;        // the only type of message a will receive        Chatting cm;        // the date I connect        String date;        // Constructore        Employeeth(Socket socket) {            // a unique id            id = ++uID;            this.socket = socket;            /* Creating both Data Stream */            System.out.println(“Thread trying to create Object Input/Output Streams”);            try {                // create output first                output = new ObjectOutputStream(socket.getOutputStream());                input = new ObjectInputStream(socket.getInputStream());                // read the username                uName = (String) input.readObject();                display(uName + ” just connected.”);            } catch (IOException e) {                display(“Exception creating new Input/output Streams: ” + e);                return;            } // have to catch ClassNotFoundException            // but I read a String, I am sure it will work            catch (ClassNotFoundException e) {            }            date = new Date().toString() + ”
“;        }        // what will run forever        public void run() {            // to loop until LOGOUT            boolean keepGoing = true;            while (keepGoing) {                // read a String (which is an object)                try {                    cm = (Chatting) input.readObject();                } catch (IOException e) {                    display(uName + ” Exception reading Streams: ” + e);                    break;                } catch (ClassNotFoundException e2) {                    break;                }                // the messaage part of the ChatMessage                String message = cm.getMessage();                // Switch on the type of message receive                switch (cm.getType()) {                    case Chatting.MESSAGE:                        broadcast(uName + “: ” + message);                        break;                    case Chatting.LOGOUT:                        display(uName + ” disconnected with a LOGOUT message.”);                        keepGoing = false;                        break;                    case Chatting.USERS:                                                for (int i = 0; i < employe.size(); ++i) {                            Employeeth ct = employe.get(i);                            writeMsg((i + 1) + ") " + ct.uName + " since " + ct.date);                        }                        break;                }            }                    }        // try to close everything        private void close() {            // try to close the connection            try {                if (output != null) {                    output.close();                }            } catch (Exception e) {            }            try {                if (input != null) {                    input.close();                }            } catch (Exception e) {            };            try {                if (socket != null) {                    socket.close();                }            } catch (Exception e) {            }        }        /* * Write a String to the Client output stream         */        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 {                output.writeObject(msg);            } // if an error occurs, do not abort just inform the user // if an error occurs, do not abort just inform the user            catch (IOException e) {                display("Error sending message to " + uName);                display(e.toString());            }            return true;        }    }}

Post Author: admin

x

Hi!
I'm Erica!

Would you like to get a custom essay? How about receiving a customized one?

Check it out