MatiasMerkuri
3/13/2019 - 2:12 PM

Instant Messaging Program

INSTANT MESSAGING PROGRAM WHICH USES SOCKETS, STREAMS ETC. IT CAN CONNECT TO A SERVER THROUGH A PORT AND BE ABLE TO SEND MESSAGES TO THE CLIENT AND VICE-VERSA

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server extends JFrame {

    private JTextField userMsg;
    private JTextArea msgWindow;
    private ObjectOutputStream output;
    private ObjectInputStream input;
    private ServerSocket server;
    private Socket connection;

    public Server(){
        super("Instant Messenger");
        userMsg = new JTextField();
        userMsg.setEditable(false);

        // Listens for ENTER and when clicked will replace the text on the text bar with blank, as it has been sent.
        userMsg.addActionListener(
                new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        sendMsg(e.getActionCommand());
                        userMsg.setText("");
                    }
                }
        );

        add(userMsg, BorderLayout.NORTH);
        msgWindow = new JTextArea();
        add(new JScrollPane(msgWindow));
        setSize(600, 450);
        setVisible(true);
        msgWindow.setEditable(false);

    }

    // Core method. Will be run in the main method, this will virtually begin the whole process
    public void startRunning(){
        try{
            server = new ServerSocket(6789, 100);
            while(true){
                try{
                    waitForConn();
                    setupStreams();
                    whileChatting();
                } catch (EOFException eofeException) {
                    showMsg("\nConnection Terminated");
                } finally {
                    close();
                }
            }
        } catch (IOException ioException){
           ioException.printStackTrace();
        }
    }

    // waitForConn method which will wait for a connection from a client
    private void waitForConn() throws IOException{
           showMsg("Waiting for connection...");
           connection = server.accept();
           showMsg("\nConnected to " + connection.getInetAddress().getHostName());
    }

    // setupStreams method which will setup the streams
    private void setupStreams() throws IOException{
        output = new ObjectOutputStream(connection.getOutputStream());
        output.flush();

        input = new ObjectInputStream(connection.getInputStream());
        showMsg("\nStreams established \n ");
    }

    // whileChatting method which will run whilst there is a connection unless the CLIENT TERMINATED the connection.
    // It will treat the object passed as a String
    private void whileChatting() throws IOException{
        String msg = " Connected to client ";
        sendMsg(msg);
        ableToType(true);

        do{
            try{
                msg = (String) input.readObject();
                showMsg("\n" + msg);
            } catch (ClassNotFoundException classNotFoundException) {
                showMsg("\n Error");

            }
        } while (!msg.equals("CLIENT - TERMINATE"));
    }

    // close method which will close all the sockets & connection
    private void close(){
        showMsg("\n Terminating connections... \n ");
        ableToType(false);
        try{
            output.close();
            input.close();
            connection.close();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

    // sendMsg method will be used for for the sending of the msgs from the server
    private void sendMsg(String msg){
        try{
            output.writeObject("SERVER - " + msg);
            output.flush();
            showMsg("\nSERVER - " + msg);
        } catch (IOException ioException) {
            msgWindow.append("\n Error: Could not send message");
        }
    }

    // showMessage method which basically sends a message in the msgWindow
    private void showMsg(final String txt){
        SwingUtilities.invokeLater(
                new Runnable() {
                    @Override
                    public void run() {
                        msgWindow.append(txt);
                    }
                }
        );
    }

    // ableToType method which will revoke or grant permission to type in the text bar based on the boolean passed
    private void ableToType(final boolean tOf){
        SwingUtilities.invokeLater(
                new Runnable() {
                    @Override
                    public void run() {
                        userMsg.setEditable(tOf);
                    }
                }
        );
    }

}
import javax.swing.*;

public class ServerTest {
    public static void main(String args[]){

        Server server = new Server();
        server.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        server.startRunning();
    }
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class Client extends JFrame {

    private JTextField userTxt;
    private JTextArea msgWindow;
    private ObjectOutputStream output;
    private ObjectInputStream input;
    private String msg = "";
    private String serverIP;
    private Socket connection;

    public Client(String host){

        super("Title");
        serverIP = host;
        userTxt = new JTextField();
        userTxt.setEditable(false);

        // Listens for ENTER and when clicked will replace the text on the text bar with blank, as it has been sent.
        userTxt.addActionListener(
                new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        sendMessage(e.getActionCommand());
                        userTxt.setText("");
                    }
                }
        );

        add(userTxt, BorderLayout.NORTH);
        msgWindow = new JTextArea();
        add(new JScrollPane(msgWindow), BorderLayout.CENTER);
        setSize(300, 150);
        setVisible(true);

    }

    // Core method. Will be run in the main method, this will virtually begin the whole process
    public void startRunning(){
        try{
            connectToServer();
            setupStreams();
            whileChatting();
            // Handling EOFExceptions
        } catch (EOFException eofException){
            showMessage("\nClient terminated connection");
            // Handling IOExceptions
        } catch (IOException ioException){
            ioException.printStackTrace();
        } finally {
            close();
        }
    }

    // Connect to server method, which will create a socket, connect to the server IP and go through the open port specified
    private void connectToServer() throws IOException{
        showMessage("Attempting connection... \n");
        connection = new Socket(InetAddress.getByName(serverIP), 6789);
        // Message showing that the two clients are connected
        showMessage("Connected to: " + connection.getInetAddress().getHostName());
    }

    // Setting up the input and output streams
    private void setupStreams() throws IOException{

        // Setting the output stream
        output = new ObjectOutputStream(connection.getOutputStream());
        // Flushing the leftover bytes
        output.flush();

        // Setting up the input stream
        input = new ObjectInputStream(connection.getInputStream());
        showMessage("\nStreams established \n");
    }

    // whileChatting method which will read the object passed through and treat it as a string. It will keep running whilst a TERMINATE message has not been sent
    private void whileChatting() throws IOException{
        ableToType(true);
        do {
            try{
                msg = (String) input.readObject();
                showMessage("\n" + msg);
            } catch (ClassNotFoundException classNotFoundException){
                showMessage("\n Could not identify object type ");
            }
        } while (!msg.equals("SERVER - TERMINATE"));
    }

    // Close method which will close the streams, the connection, and will revoke the permission from the user to type into the text bar
    private void close() {
        showMessage("\n Connection terminated");
        ableToType(false);
        try {
            output.close();
            input.close();
            connection.close();
        } catch (IOException ioException){
            ioException.printStackTrace();
        }
    }

    // sendMessage method which will write the object sent (a string) so there is a username (CLIENT)
    private void sendMessage(String msg){
        try{
            output.writeObject("CLIENT - " + msg);
            output.flush();
            showMessage("\n CLIENT - " + msg);
        } catch (IOException ioException){
            msgWindow.append("\n Something went wrong ");
        }
    }

    // showMessage method which basically sends a message in the msgWindow
    private void showMessage(final String msg){
        SwingUtilities.invokeLater(
                new Runnable() {
                    @Override
                    public void run() {
                        msgWindow.append(msg);
                    }
                }
        );
    }

    // abletoType method which will revoke or grant permission to type in the text bar based on the boolean passed
    private void ableToType(final Boolean tOf){
        SwingUtilities.invokeLater(
                new Runnable() {
                    @Override
                    public void run() {
                        userTxt.setEditable(tOf);
                    }
                }
        );
    }

}
import javax.swing.*;

public class ClientTest {
    public static void main(String args[]){
        Client client = new Client("127.0.0.1");
        client.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        client.setVisible(true);
        client.startRunning();
    }
}