Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: My instant messanger program doesn't work completely!

  1. #1
    Junior Member
    Join Date
    Aug 2013
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Post My instant messanger program doesn't work completely!

    Hello!
    I currently built a very simple chatting program by following this tutorial:
    Intermediate Java - 59 - Running Buckys Instant Messenger!



    But I have a problem in my instance messenger program. Here I explain:
    My program runs fine, but the problem is that if I write message on the client part's chat window, it doesn't send that to server window. But the server part works good and it can send the message to the client window.
    As I guess that I may have problem with the local host address: 127.0.0.1
    And thats why my message can't be delevered to the server part.

    The codes from my program are shown below: All codes from server and client parts including their main classes are given in the "java code" box



    /*
     
    [COLOR="#008000"]Server program:[/COLOR]
     
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package im;
     
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
     
    /**
     * /**
     * /**
     * /**
     * /**
     * /**
     *
     * @author Jabir Al Fatah
     */
    public class Server extends JFrame {
     
        private JTextField usertext;
        private JTextArea chatWindow;
        private ServerSocket server;
        private Socket connection;
        private ObjectOutputStream output;
        private ObjectInputStream input;
        private String ms;
        //ms= "Please wait to get connection...";
     
        public Server() {
            super("ICool Messanger");
     
     
            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(400, 300);
            setVisible(true);
     
        }
        //This codes are for setting up and running the server.
     
        public void startRunning() {
     
            try {
                server = new ServerSocket(6789, 100);
                while (true) {
                    try {
                        waitForConnection();
                        setUpStream();
                        whileChatting();
     
     
                    } catch (EOFException eofException) {
                        showMessage("\n The connection is ended");
                    } finally {
                        closeCrap();
                    }
                }
     
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
     
        public void waitForConnection() throws IOException {
            ms = "Please wait to get connection...\n";
            showMessage(ms);
            //ms.editable(false);
            //showMessage("Please wait to get connection...\n");
            //showMessage.setEditable(false);
            connection = server.accept();
            showMessage("Now you are connected to" + connection.getInetAddress().getHostAddress());
     
     
        }
     
        public void setUpStream() throws IOException {
            output = new ObjectOutputStream(connection.getOutputStream());
            output.flush();
            input = new ObjectInputStream(connection.getInputStream());
            showMessage("\n The streams are now setup");
     
        }
     
        public void whileChatting() throws IOException {
            String message = "Congratulation! You are now connected";
            sendMessage(message);
            ableToType(true);
            do {
                try {
                    message = (String) input.readObject();
                    //showMessage("\n" + message);
                } catch (ClassNotFoundException classNotfoundException) {
                    showMessage("\nThe input is not recognizable, please enter any text");
                }
                //} while (!message.equals("SERVER-END"));
            } while (!message.equals("CLIENT-END"));
     
     
     
     
     
     
        }
     
        private void closeCrap() {
            showMessage("\nClosing crap...\n");
            ableToType(false);
            try {
                output.close();
                input.close();
                connection.close();
            } catch (IOException ioexception) {
                ioexception.printStackTrace();
            }
        }
     
        private void sendMessage(String message) {
            try {
                output.writeObject("SERVER-" + message);
                output.flush();
                showMessage("\nSERVER-" + message);
            } catch (IOException ioexception) {
                chatWindow.append("\nThere may be an error, contact the service provider!");
     
            }
        }
     
        private void showMessage(final String text) {
            SwingUtilities.invokeLater(
                    new Runnable() {
                public void run() {
                    chatWindow.append(text);
                }
            });
        }
     
        private void ableToType(final boolean tof) {
            SwingUtilities.invokeLater(
                    new Runnable() {
                public void run() {
                    usertext.setEditable(tof);
                }
            });
        }
    }
     
     
    [U][B][I]Main class[/I][/B][/U]
     
     
     
    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    package im;
     
    import javax.swing.JFrame;
     
    /**
    *
    * @author Jabir Al Fatah
    */
    public class IM {
     
    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {
    Server sr = new Server();
    sr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    sr.startRunning();
    // TODO code application logic here
    }
    }
     
     
    [COLOR="#008000"]Client program:[/COLOR]
     
    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    package imclient;
     
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
     
    /**
    *
    * @author Jabir Al Fatah
    */
    public class Client extends JFrame {
     
    private JTextField usertext;
    private JTextArea chatwindow;
    private Socket connection;
    private ObjectInput input;
    private ObjectOutput output;
    private String message = "";
    private String ServerIP;
     
    public Client(String host) {
    super("My ICool messanger");
    ServerIP = host;
    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), BorderLayout.CENTER);
     
    setSize(300, 200);
    setVisible(true);
     
     
     
    }
     
    public void startRunning() {
    try {
    connectToServer();
    setupStreams();
    whileChatting();
     
     
     
     
     
    } catch (EOFException eofException) {
    showMessage("\n You aren't connected anymore");
     
    } catch (IOException iOException) {
    iOException.printStackTrace();
    } finally {
    closeCrap();
    }
    }
     
    private void connectToServer() throws IOException {
     
    showMessage("Attempting connection");
    connection = new Socket(InetAddress.getByName(ServerIP), 6789);
    showMessage("\n Connected to :" + connection.getInetAddress().getHostName());
    }
     
    private void setupStreams() throws IOException {
    output = new ObjectOutputStream(connection.getOutputStream());
    output.flush();
     
    input = new ObjectInputStream(connection.getInputStream());
    showMessage("\nYour streams are now setup");
    }
     
    private void whileChatting() throws IOException {
    ableToType(true);
    do {
    try {
    message = (String) input.readObject();
    showMessage("\n" + message);
     
    } catch (ClassNotFoundException classNotFoundException) {
    showMessage("I can't read the object");
    }
     
     
    } while (!message.equals("SERVER-END"));
    }
     
    private void closeCrap() {
    ableToType(false);
    showMessage("\nClosing down the messanger");
    try {
    output.close();
    input.close();
    connection.close();
     
    } catch (IOException iOException) {
    //showMessage("\nThere is an error!")
    iOException.printStackTrace();
    }
     
    }
     
    private void sendMessage(String message) {
    try {
    output.writeObject("CLIENT:- " + message);
    output.flush();
    showMessage("\nCLIENT:- " + message);
    } catch (IOException iOException) {
    chatwindow.append("\nThe message can't be delevered");
     
    }
     
    }
     
    private void showMessage(final String te) {
    SwingUtilities.invokeLater(
    new Runnable() {
    public void run() {
    chatwindow.append(te);
     
     
    }
    });
     
    //private void closeCrap() {
    //}
    }
     
    private void ableToType(final boolean tof) {
    SwingUtilities.invokeLater(
    new Runnable() {
    public void run() {
    usertext.setEditable(tof);
    }
    });
     
     
    }
    }
     
     
    [B][I]Main Class:[/I][/B]
     
     
    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    package imclient;
     
    import javax.swing.JFrame;
     
    /**
    *
    * @author Jabir Al Fatah
    */
    public class IMClient {
     
    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {
    Client cl;
    cl = new Client("127.0.0.1");
    //cl = new Client("");
    //cl = new Client(" 77.105.222.248");
    cl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    cl.startRunning();
    //Client cl = new Client();
    //cl.startRunning();
     
     
    // TODO code application logic here
    }
    }
    Last edited by jabirfatah2009; August 28th, 2013 at 03:06 PM. Reason: Wrong formating of code


  2. #2
    Member
    Join Date
    Jul 2013
    Posts
    219
    Thanks
    0
    Thanked 18 Times in 17 Posts

    Default Re: My instant messanger program doesn't work completely!

    Hello.
    Using a pencil and a paper, if you would have traced your program you might have noticed the big fault in your system.
    Before reading my post further I suggest you trace it and try to find out. If your efforts still fail then read further.
    Even though you claim to call your application to be 2-way communication its actually 1-way. Where did you write the statements to send a message from client to the server. I did not notice it. Hence there is no messages sent from client to the server.
    In case you have copied the code from other source please discard it and try to develop on your own.
    I will give you the following tips:
    - Write two separate components (server and client)
    - Each component will have two threads (reader and writer) running parallelly. Reader will keep reading the incoming messages and if any displays them. Writer will keep writing the messages typed in the textfield once enter key is hit.

    Hope that helps.

    Syed.

  3. #3
    Junior Member
    Join Date
    Aug 2013
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: My instant messanger program doesn't work completely!

    Hello!
    Thank you for your quick response!
    I guess it's huge task to write the whole program all over again. I want to develop further the program in the way it's already written from the begining.
    "sendMessage" method can be the responsible part to send message from the client part and I wrote my statements in that method. Isn't it? Cabn you please discover my fault more?

Similar Threads

  1. This Program doesn't run completely, what do I need to fix? Please Help
    By shafat in forum What's Wrong With My Code?
    Replies: 8
    Last Post: August 6th, 2013, 09:04 AM
  2. Program doesn't work!
    By Mrcinica in forum What's Wrong With My Code?
    Replies: 15
    Last Post: May 16th, 2013, 10:23 AM
  3. No idea why this program doesn't work
    By Diesel298 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: November 7th, 2012, 01:01 PM
  4. Program works fine but with friend it doesn't work
    By Rizza in forum What's Wrong With My Code?
    Replies: 1
    Last Post: December 1st, 2011, 01:20 PM
  5. [SOLVED] New at Java... my if, else if, else program doesn't seem to work, skips to else.Help!
    By KevinE in forum What's Wrong With My Code?
    Replies: 4
    Last Post: November 1st, 2010, 03:51 PM