Search code examples
javaswingserversocketevent-dispatch-threadmessenger

Making Instant Messaging Program, Running Incorrectly?


I am just running the server to ensure it works. When i run ServerTest.java, I get "Closing Connections in my TextArea", However I am expected to have "Waiting for Someone to Connect..." within the textField. Could someone tell me, what my problem is?

ServerTest.java

import javax.swing.JFrame;

public class ServerTest {

    public static void main(String[] args){
        Server Spirit = new Server();
        Spirit.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Spirit.startRunning();
    }
}

Server.java

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class Server extends JFrame {

private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;

//server constructor
public Server(){
    super("SiM");
    userText = new JTextField();
    userText.setEditable(false);
    userText.addActionListener(
            new ActionListener(){
                public void actionPerformed(ActionEvent event){
                    sendMessage(event.getActionCommand());
                    userText.setText("");
                }
            }
            );
    add(userText, BorderLayout.NORTH);
    chatWindow = new JTextArea();
    add(new JScrollPane(chatWindow));
    setSize(300,150);
    setVisible(true);

}

public void startRunning(){
    try{
        server = new ServerSocket (6798, 100); // parameters port and backlog
        while(true){
            try{
                waitForConnection();//waits for a connection
                setupStreams(); //sets up connection
                whileChatting();//once connected, sends message between each other
            }catch(EOFException eofException){              
                showMessage("\n Server Ended the Connection!"); //once streams been closed by Server
            }finally{
                closeCrap();
            }
        }
    }catch(IOException ioException){
        ioException.printStackTrace();
    }


}

//connection waiting

private void waitForConnection() throws IOException{
    showMessage("Waiting for somebody to connect... \n");
    connection = server.accept(); //listens for connection made to this socket and accepts it
    showMessage("Connected to" + connection+getInetAddress().getHostName() + " \n"); //dispays ip of connected
    }

//exchange data
private void setupStreams() throws IOException{
    output = new ObjectOutputStream(connection.getOutputStream());
    output.flush(); //flushes the stream
    input = new ObjectInputStream(connection.getInputStream());
    showMessage("\n Streams Accepted \n");
}

//initiates chat
private void whileChatting() throws IOException {
    String message = "You are now Connected";
    sendMessage(message);
    ableToType(true); //allows the user to type
    do{
        try{
            message = (String) input.readObject();
            showMessage("\n"+ message); //sent messages
        }catch(ClassNotFoundException classNotFoundException){ //if something odd is sent i.e string not sent
            showMessage("\n Unknown Message Sent! \n"); 
        }
    }while(!message.equals("CLIENT - END"));
}

//closes program
private void closeCrap(){
    showMessage("\n Closing Connections... \n");
    ableToType(false);
    try{
        output.close(); //closes connection from client
        input.close(); //closes connection to client
        connection.close(); //closes socket
    }catch(IOException ioException){
        ioException.printStackTrace();
    }
}

//send message to client
private void sendMessage(String message){
    try{
        output.writeObject("ADMIN/Server -  " + message);
        output.flush();
        showMessage("\nADMIN/Server -  " + message);
    }catch(IOException ioException){
        chatWindow.append("\n Message not Sent \n");
    }

}

//update chatWindow
private void showMessage(final String text){
    SwingUtilities.invokeLater( //creates thread that will update the GUI
            new Runnable(){
                public void run(){
                    chatWindow.append(text); //adds to the end of chattWindow
                }
            }
            );
}

//to type
private void ableToType(final boolean tof){
    SwingUtilities.invokeLater( //creates thread that will update the GUI
            new Runnable(){
                public void run(){
                     userText.setEditable(tof); //updates GUI, to allow you to type
                }
            }
            );
}

}

I have been following TheNewBoston Tutorials.


Solution

  • My error was my waitForConnection() constructor

    private void waitForConnection() throws IOException{
        showMessage("Waiting for somebody to connect... \n");
        connection = server.accept(); //listens for connection made to this socket and accepts it
        showMessage("Connected to" + connection+getInetAddress().getHostName() + " \n"); //dispays ip of connected
        }
    

    On line 4 it should be "." not "+"

    + connection.getInetAddress().getHostName() +

    It was a typing error.