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 21 of 21

Thread: a private chat application in process

  1. #1
    Member
    Join Date
    Jun 2013
    Posts
    61
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default a private chat application in process

    The code of the private chat application is still in process and is still not fully working !
    (though I am close to get it working I believe). The Chat connects one computer with
    another and does not need to be at a server, like two fully equal walky talkies talking to each other
    (at least that is my idea for now).
    You may start the application two times and communicate at one single computer, using the local host
    address 127.0.0.1. But than something goes wrong, see the next error code. I should say that, that goes over my head for the moment!
    Important is, when you connect one application with the other using the local host, you can chat only in
    one direction (which also flies over my head for the moment)


    01-ago-2013 22:41:45 privatechat.Main$SocketConnection run
    GRAVE: null
    java.net.BindException: Address already in use
    at java.net.PlainSocketImpl.socketBind(Native Method)
    at java.net.PlainSocketImpl.bind(PlainSocketImpl.java :383)
    at java.net.ServerSocket.bind(ServerSocket.java:328)
    at java.net.ServerSocket.<init>(ServerSocket.java:194 )
    at java.net.ServerSocket.<init>(ServerSocket.java:106 )
    at privatechat.Main$SocketConnection.run(Main.java:34 6)
    Exception in thread "Thread-3" java.lang.NullPointerException
    at privatechat.Main$SocketConnection.run(Main.java:40 9)

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
     
    package privatechat;
     
     
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.ComponentOrientation;
    import java.awt.Container;
    import java.awt.FlowLayout;
    import java.awt.Font;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    import javax.swing.event.MenuEvent;
     
    /**
     *
     * @author willem
     * This private chat application shows your IP and waits,
     * through a socket connect loop, for the peer chatter to contact you.
     * When given the correct peer IP and by pushing "connect" the wait-loop
     * breaks off and a new socket connection starts to connect with the peer chatter.
     * After the proper handshake the receiver/ info text-area invites you
     * to send a greeting (or prints an error when the connections did not work out)
     * and the chat may begin (or not)!
     *
     */
    public class Main extends JFrame { // the main class sets the GUI and the listeners
        private Color bluecolor, blackcolor, redcolor;
        private Font theFont;
        private int port;
        private JTextField ipIn, ipOut;
        private JButton send, connect, save;
        private JComboBox scriptBox;
        private JTextArea textIn, textOut;
        private JLabel ipInLabel, ipOutLabel, scriptLabel, incomeChat, outcomeChat;
        private JCheckBoxMenuItem checkbmenu1;
        private ActionListener menuListener;
        private ActionListener panelListener;
        private SocketConnection sc1, sc2;
        private enum SocketState {LISTENING, ME_CONNECTING}
        private SocketState state;
        private String handshake, ip;
     
     
        public Main() {
                bluecolor = Color.BLUE;
                redcolor = Color.RED;
                blackcolor = Color.BLACK;
                theFont = new Font("SansSerif", Font.PLAIN, 14);
                port = 1501;
                handshake = "willemprivatechat";
                menuListener = new MenuListener();
                panelListener = new panelListener();
     
                addWindowListener( new WindowAdapter() {
                        public void windowClosed(WindowEvent evt) {
     
     
                        }
                });
     
                Container contentPane = getContentPane();
                contentPane.add(CreateGuiPanel());
                getIP();
                setJMenuBar(createMenubars());        
                sc1 = new SocketConnection(1501); // the call awaiting constructor
        }
     
        public static void main(String[] args)  {
            JFrame frame = new Main();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setTitle("PRIVATE CHAT");
            frame.setBounds(300, 300, 700, 600);
            frame.setResizable(false);
            frame.setVisible(true);
        }
     
     
        public JPanel CreateGuiPanel()  { // all the GUI for the chat panel
            // three buttons: connect, send, and save the text
            send = new JButton("send");
            send.setActionCommand("SEND");
            send.addActionListener(panelListener);
            connect = new JButton("connect");
            connect.setActionCommand("CONNECT");
            connect.addActionListener(panelListener);
            save = new JButton("save all the chat text");
            save.setActionCommand("SAVE");
            save.addActionListener(panelListener);
     
            //the text labels for the components
            ipInLabel = new JLabel ("My IP address    ");
            ipOutLabel = new JLabel("Peer's IP address");
            scriptLabel = new JLabel("Enscript the chat");
     
            // two IP textfields
            ipIn = new JTextField(12);
            ipIn.setText("");
            ipIn.requestFocusInWindow();
            ipIn.setMaximumSize(ipIn.getPreferredSize());
            ipInLabel.setLabelFor(ipIn);
            ipIn.setEditable(false);
            ipOut = new JTextField(12);
            ipOut.setText("");
            ipOut.requestFocusInWindow();
            ipOut.setMaximumSize(ipIn.getPreferredSize());
            ipOutLabel.setLabelFor(ipOut);
            ipOut.setEditable(true);
     
            // two chat text field/ area
     
            textIn = new JTextArea(20,55);
            textIn.setLineWrap(true);
            textIn.setWrapStyleWord(true);
        //    textIn.setPreferredSize(new Dimension(30,10));
            textIn.setText("The Private Chat Application\n"
                             + "is waiting to get connected.\n"
                             + "when you know your peer's IP\n"
                             + "write it into the box and push\n"
                             + "connect and have fun.\n \n");
            textIn.setFont(new Font("Serif", Font.ITALIC, 16));
            textIn.setEditable(true);
            textOut = new JTextArea(4,50);
            textOut.setLineWrap(true);
            textOut.setWrapStyleWord(true);
        //    textOut.setPreferredSize(new Dimension(200,30));
            textOut.setFont(new Font("Serif", Font.ITALIC, 16));
            textOut.setEditable(true);
     
            JScrollPane scrollPanel1 = new JScrollPane(textIn);
            JScrollPane scrollPanel2 = new JScrollPane(textOut);
     
            //the enscript combo box
            String[] scriptitems = {"No Script"};
            scriptBox = new JComboBox(scriptitems);
            scriptBox.setSelectedIndex(0);
            scriptBox.addActionListener(menuListener);
            scriptBox.setActionCommand("COMBO");
     
            //the panel setups and named borders
            JPanel mainPanel = new JPanel(new BorderLayout());
     
      //      JPanel southPanel = new JPanel(new GridLayout(2, 0));
      //      JPanel centerPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
      //      JPanel northPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
     
            JPanel southPanel = new JPanel(new GridLayout(2, 1));
            JPanel centerPanel = new JPanel(new FlowLayout(FlowLayout.CENTER,3,3));
            JPanel northPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
     
            JPanel northbuttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
            JPanel southbuttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
            JPanel fieldPanel = new JPanel(new GridLayout(2, 1));
            JPanel ipInPanel = new JPanel(new GridLayout(1, 2));
            JPanel ipOutPanel = new JPanel(new GridLayout(1, 2));
            JPanel buttonCombo = new JPanel(new FlowLayout(FlowLayout.RIGHT));
     
            JPanel textPanel = new JPanel(new GridLayout(2, 1));
     
     
            // the south panel
            ipInPanel.add(ipInLabel);
            ipInPanel.add(ipIn);
            ipOutPanel.add(ipOutLabel);
            ipOutPanel.add(ipOut);
     
            fieldPanel.add(ipInPanel);
            fieldPanel.add(ipOutPanel);
            southPanel.add(fieldPanel);
            buttonCombo.add(connect);
            buttonCombo.add(scriptBox);
            northPanel.add(fieldPanel);
            northPanel.add(buttonCombo);
     
            //the center panel
            centerPanel.setBackground(Color.WHITE);
            centerPanel.add(scrollPanel1);
     
            //the north panel
            JPanel textoutPanel = new JPanel(new FlowLayout());
            textoutPanel.add(scrollPanel2);
            textoutPanel.add(send);
            southbuttonPanel.add(save);
            southPanel.add(textoutPanel);
            southPanel.add( southbuttonPanel);
     
            // all of the chat panel
     
            mainPanel.add(centerPanel, BorderLayout.CENTER);
            mainPanel.add(northPanel, BorderLayout.NORTH);
            mainPanel.add(southPanel, BorderLayout.SOUTH);
     
     
            return mainPanel;
        }
     
        public JMenuBar createMenubars()  { // the menubar plus items (not working yet)
            JMenuBar menuBar = new JMenuBar();
            JMenu setup = new JMenu("More Options");
            checkbmenu1 = new JCheckBoxMenuItem("test");
     
            checkbmenu1.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
            checkbmenu1.setHorizontalAlignment(checkbmenu1.LEADING);
         //   menuItem1.setMnemonic(KeyEvent.VK_C);
            JCheckBoxMenuItem checkbmenu2 = new JCheckBoxMenuItem("select all");
     
            checkbmenu2.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
            checkbmenu2.setHorizontalAlignment(checkbmenu2.LEADING);
            JMenuItem menuItem1 = new JMenuItem("Handshake");
            JMenuItem menuItem2 = new JMenuItem("Set Port");
            JMenuItem menuItem3 = new JMenuItem("Send File");
            JMenuItem menuItem4 = new JMenuItem("Quit");
     
     
            menuItem1.addActionListener(menuListener);
            menuItem2.addActionListener(menuListener);
            menuItem3.addActionListener(menuListener);
            menuItem4.addActionListener(menuListener);
            checkbmenu1.addActionListener(menuListener);
            checkbmenu2.addActionListener(menuListener);
     
            setup.add(menuItem1);
            setup.add(menuItem2);
            setup.add(checkbmenu1);
            setup.add(checkbmenu2);
            setup.add(menuItem3);
            setup.add(menuItem4);
            menuBar.add(setup);
            return menuBar;
        }
     
     
       public void getIP() { // gets the IP of this computer
            String st = "";
            try {
                st = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException ex) {
                textIn.setText("can not get the IP of this computer " + ex + "\n");
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
     
            if (st.equals("127.0.0.1"))
                ipIn.setText("no connection" + "\n");
            else
                ipIn.setText(st);
       } // end of getIP()
     
     
     
       class MenuListener implements ActionListener { // not working yet
     
                public void menuSelected(MenuEvent me) {
     
                }
     
                public void menuDeselected(MenuEvent me) {
     
                }
     
                public void menuCanceled(MenuEvent me) {
     
                }
     
            public void actionPerformed(ActionEvent ae) {
     
            }
       }
     
         class panelListener implements ActionListener {
     
     
            public void actionPerformed(ActionEvent e) {
                String cmd = e.getActionCommand();
     
     
                if (cmd.equals("CONNECT")) {
                        // close the income waiting loop
                        sc1.closeConnection();
                        // start the outgoing call constructor
                        sc2 = new SocketConnection(ipOut.getText(), port); 
                }
                if (cmd.equals("SEND")) { // sends the chat message
                    String line = null;
                    line = textOut.getText();                
                    textIn.append("Me: " + line + "\n");
                    textOut.setText("");
                    sc2.transmite().println(line + "\n");  // text send out of chat
                }
                if (cmd.equals("SAVE")) { // not working
                    System.out.println("save");
                }
            }
       }
     
      /**
     *
     * The second private inner class takes care of the socket connections.
     *
     *
     *
     */
     
     
        private class SocketConnection extends Thread {
            private int port;
            private String ip = null;
            private Socket socket;
            PrintWriter socketout;
            private ServerSocket s = null;
     
            public SocketConnection(int port)  {
                state = SocketState.LISTENING; // incoming/ waiting for caller
                this.port = port;
                start();
            }
     
            public SocketConnection(String ip, int port)  {
                state = SocketState.ME_CONNECTING; // calling out to peer
                this.ip = ip;
                this.port = port;
                start();
            }
     
            public void run() {
     
                try {
                    if (state == SocketState.LISTENING)  {
                        s = new ServerSocket(port);
                        textIn.append("    listening on incoming calls \n ");
                        /* Here, waiting for the peer to connect.
                        *  When connected the waiting socket "s" shuts down.
                        *  The waiting clause gets interrupted when the
                        *  application calls out to the peer through "connect".
                        *  For this action one needs the IP of the peer.
                        */
                        socket = s.accept();
                        s.close();
     
                        textIn.setText("\n" +
                                "listening on incoming is clossed \n" +
                                "connecting with incoming call \n");
                    }
                    else
                    /* From here, the application calls out.
                     * It is important to know that the same application
                     * waits for calls and calls out actively, which might be
                     * an error?
                     *
                     */
     
                    if (state == SocketState.ME_CONNECTING){
                        textIn.append("   starting connection out on:  " + ip +
                                "   port: " + port + "\n\n");
     
                        String idString = ipIn.getText(); //get the peer internet IP
     
                        socket = new Socket(idString, port);
                      //  socket.setSoTimeout(10000); // time out after 10 seconds
                    }
                    /* From here on a connection is established, either
                     * passive or active and the chat routine of Me and Peer
                     * should begin....
                     *
                     */
     
                }
                catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
     
                try { // reading and sending text lines
                       String linein;
                       BufferedReader socketin = new BufferedReader (new
                                    InputStreamReader(socket.getInputStream()));
                       // the socketout is connected with the "send" button
                       // see at the buttom the transmite method!
                       socketout = new PrintWriter
    				(socket.getOutputStream(), true /*autoFlush */);
     
                       while ((linein = socketin.readLine()) != null) {
                                textIn.append("peer: " + linein + "\n");
     
    		   }
    	    }
     
                catch(Exception e) {
    			//handle exception
    	    }
                finally  {
                    try {
                        socket.close();
                    } catch (IOException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    }
                            textIn.append("socket is clossed" + "\n");
                }
    	} // end of the run method
     
            public boolean Handschake(String handshake, String hnd)  { // not working yet
                if (handshake.equals(hnd))
                return true;
                else
                return false;
            }
     
            public PrintWriter transmite()  { // communicating with the GUI main clase
                return socketout;
            }
     
     
     
            synchronized void closeConnection() { // clean up the sockets
                try {
                    if (socket != null)
                         socket.close();
                    if (s != null)
                         s.close();         
                }
                catch (IOException ex) {
                }
            }
     
     
        } // end of the inner class
     
    }


    --- Update ---

    Ok the error message is obvious, when running on the same machine and using local host:
    socket error java.net.BindException: Address already in use...
    So one has to try the application on different machines, or any other suggestion?


  2. #2
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: a private chat application in process

    It is most likely the port is being held open by a previous run of the application in question.
    Make sure to close the sockets and terminate any threads when the application is closed.

    There should be no problem running both on one machine at the same time

  3. #3
    Member
    Join Date
    Jun 2013
    Posts
    61
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: a private chat application in process

    jps, the error appears when opening for the second time the chat and both are open and listening through a socket on port 1501 over the local address. No program is closed yet and both are waiting for income calls (LISTENING):

    try {
                    if (state == SocketState.LISTENING)  {
                        s = new ServerSocket(port);
                        textIn.append("    listening on incoming calls \n ");
                        /* Here, waiting for the peer to connect.
                        *  When connected the waiting socket "s" shuts down.
                        *  The waiting clause gets interrupted when the
                        *  application calls out to the peer through "connect".
                        *  For this action one needs the IP of the peer.
                        */
                        socket = s.accept(); // <- both programs waiting here
                        s.close();

    but a "socket error java.net.BindException: Address already in use" appears when opening the second (equal) program!
    (understand please that one opens the same identical program two time on the same machine and maybe here lays the problem, because the program should be opened on two different machines, which I have to try out still....)
    The idea is that one of the (equal) application calls out to the other, when this happens (pushing
    connect button), it will close the (waiting) socket (on one of the app) and start a new thread (the threads start at the two constructors of the inner class (?)):


    if (cmd.equals("CONNECT")) {
                        // close the income waiting loop
                        sc1.closeConnection(); // !!!
                        // start the outgoing call constructor
                        sc2 = new SocketConnection(ipOut.getText(), port);

    the sc2 object starts a new thread now with ME_CONNECTING:


    if (state == SocketState.ME_CONNECTING){
                        textIn.append("   starting connection out on:  " + ip +
                                "   port: " + port + "\n\n");
     
                        String idString = ipIn.getText(); //get the peer internet IP
     
                        socket = new Socket(idString, port);




    Two questions for the moment:
    1) why appears the error?
    2) what happens with the first thread/ since there is no way to terminate a thread (stop kill etc. is deprecated)?

  4. #4
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: a private chat application in process

    Quote Originally Posted by willemjar View Post
    the error appears when opening for the second time the chat and both are open and listening through a socket on port 1501 over the local address
    Quote Originally Posted by willemjar View Post
    (understand please that one opens the same identical program two time on the same machine and maybe here lays the problem
    bingo
    Quote Originally Posted by willemjar View Post
    because the program should be opened on two different machines
    not when you get it done correctly
    I suggest a tutorial on server client communications, especially the use of server sockets.
    Roughly the problem is the repeated attempt to open two server sockets on the same port, which is not necessary, or allowed
    Quote Originally Posted by willemjar View Post
    what happens with the first thread/ since there is no way to terminate a thread (stop kill etc. is deprecated)?
    What a world this would be if that were true. Try a search for starting/stopping threads. There are many ways.

    There is a tutorial on Oracle using knock knock jokes, but the last time I looked at it there was a bug, and to copy-paste it did not work correctly. Try to find a tutorial that shows the use of a server socket to establish multiple connections

  5. #5
    Member
    Join Date
    Jun 2013
    Posts
    61
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: a private chat application in process

    So I am testing it now on two comp and different IPs
    Both computers are waiting for incoming calls:

    server = new ServerSocket(port);
    textIn.append(" listening on incoming calls \n ");
    socket = server.accept();

    Than one calls out (the other still on the server socket), by
    first ending the server socket:

    if (server != null && !server.isClosed())
    server.close();

    which gives me a (error) catch.....
    Is that normal?

    04-ago-2013 19:46:17 privatechat.Main$SocketConnection run
    GRAVE: null
    java.net.SocketException: Socket closed
    at java.net.PlainSocketImpl.socketAccept(Native Method)
    at java.net.PlainSocketImpl.accept(PlainSocketImpl.ja va:408)
    at java.net.ServerSocket.implAccept(ServerSocket.java :462)
    at java.net.ServerSocket.accept(ServerSocket.java:430 )
    at privatechat.Main$SocketConnection.run(Main.java:35 0)


    BTW what is GRAVE: null?

    In short: I am asking how to close a server socket
    that is waiting for ever?

    --- Update ---

    Found this on the net! Is this a smart why in handling the server:

    ServerSocket server = new ServerSocket();
    server.setSoTimeout(1000); // 1 second, could change to whatever you like
     
    while (running) { // running would be a member variable
         try {
             server.accept(); // handle the connection here
         }
         catch (SocketTimeoutException e) {
              // You don't really need to handle this
         }
    }

  6. #6
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: a private chat application in process

    Quote Originally Posted by willemjar View Post
    Is this a smart why in handling the server:
    ServerSocket server = new ServerSocket();
    server.setSoTimeout(1000); // 1 second, could change to whatever you like
     
    while (running) { // running would be a member variable
         try {
             server.accept(); // handle the connection here
         }
         catch (SocketTimeoutException e) {
              // You don't really need to handle this
         }
    }
    That would depend on what you do where it says "handle the connection here", but it is a start. Probably something like pass the newly connected client to a thread (possibly from a pool) to actually handle the client leaving the server to accept the next client.
    Oracle chapter 14 Thread Pools

  7. #7
    Member
    Join Date
    Jun 2013
    Posts
    61
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: a private chat application in process

    Thanks JPS, the next code would precede the connection, right?
    But when I run the counter connecting part I get a null pointer
    for the socket (not server socket), see code fragment pls
    (could that be the fire wall?):


    socket = server.accept();
    server.close();
     
    try { // reading and sending text lines
                       String linein;
                       BufferedReader socketin = new BufferedReader (new
                                    InputStreamReader(socket.getInputStream()));
                       // the socketout is connected with the "send" button
                       // see at the buttom the transmite method!
                       socketout = new PrintWriter
    				(socket.getOutputStream(), true /*autoFlush */);
     
                       while ((linein = socketin.readLine()) != null) {
                                textIn.append("peer: " + linein + "\n");
     
    		   }
    } plus catch
     
     
    But I am getting a null for the socket at the counter part of the connection:
     
     if (state == SocketState.ME_CONNECTING){
                        socket = null;
                        socket = new Socket(ip, port);
     
                        textIn.append("   connecting with  " + ip +
                                "   port: " + port + "\n\n");
     
                        socket.setSoTimeout(5000); // time out after 10 seconds
      } // when the connections is established it directs to the try block up

  8. #8
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: a private chat application in process

    Quote Originally Posted by willemjar View Post
    But I am getting a null for the socket at the counter part of the connection:
    I do not understand what this means.
    Again I suggest following a tutorial. Get a client to connect to an echo server. Once that is working move on to the next step

  9. #9
    Member
    Join Date
    Jun 2013
    Posts
    61
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: a private chat application in process

    I did read all that stuff and many more, jps.
    But I found another problem that may cause the socket to be null.
    I thought that the next method gives my the IP of my net work connection.
    It turns to be 192.168.1.11! Which is, I know now, the rooter IP.

    So found the second code of which the first output is kind of cryptic!
    What is it, some hex number of the ip, and if so how does one get
    the nice aaa.bbb. etc format?




    String st = "";
            try {
                st = InetAddress.getLocalHost().getHostAddress();
              //  st = InetAddress.getHostAddress();
            } catch (UnknownHostException ex) {
                textIn.setText("can not get the IP of this computer " + ex + "\n");
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
     
            if (st.equals("127.0.0.1"))
                ipIn.setText("no connection" + "\n");
            else
                ipIn.setText(st);

    ++++++++++++++++++++++++

    Enumeration e = null;
            try {
                e = NetworkInterface.getNetworkInterfaces();
            } catch (SocketException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
                while(e.hasMoreElements())
                {
                    NetworkInterface n=(NetworkInterface) e.nextElement();
                    Enumeration ee = n.getInetAddresses();
     
                    while(ee.hasMoreElements())
                    {
                        InetAddress i= (InetAddress) ee.nextElement();
                        System.out.println(i.getHostAddress());
                    }
                }


    --- Update ---

    I tried the code of
    http://www.javaprogrammingforums.com...nected-me.html
    and got this etc.

    /192.168.1.1 machine is turned on and can be pinged
    192.168.1.2/192.168.1.2 the host address and host name are equal, meaning the host name could not be resolved
    192.168.1.3/192.168.1.3 the host address and host name are equal, meaning the host name could not be resolved

  10. #10
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: a private chat application in process

    This and this provide some helpful information.
    As a side note, a search engine with "Whats my ip" should give you the public ip of the machine

  11. #11
    Member
    Join Date
    Jun 2013
    Posts
    61
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: a private chat application in process

    JPS, I can't get the application going, really annoying!
    I do not know where the problem lays (IP Socket, null or closed etc.)
    So lets go through it step by step, ok?

    First there is the "call waiting" situation of the server socket
    and here is you suggested code with some comments and questions of me:

    -if I want to end the server.accept() loop; I have to set running to false,right?
    -If running is false one jumps out of the while-loop (I tried that out), but what
    happens with the statement: server.accept():
    should I still do server.close(); (I believe yes. was checking with server.isClosed())
    The catch is not applied when jumping out the while loop, ought!?
    -but before closing I would do this: socket = server.accept();
    to have the socket for the chat going, right?

    The waiting server.accept(); runs in a thread (of which the object is called sc1)
    and the socket in another (of which the object is called sc2),
    so could I do this:
    if (sc1.Serverclossed())
    sc1.interrupt();
    since it is not doing anything else.....


    ServerSocket server = new ServerSocket();
    server.setSoTimeout(1000); // 1 second, could change to whatever you like
     
    while (running) { // running would be a member variable
         try {
             server.accept(); // handle the connection here
         }
         catch (SocketTimeoutException e) {
              // You don't really need to handle this
         }
    }

  12. #12
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: a private chat application in process

    Quote Originally Posted by willemjar View Post
    and here is you suggested code with some comments and questions of me:
    -if I want to end the server.accept() loop; I have to set running to false,right?
    No, I never suggested you set anything false. In fact the "server loop" can (and should) continue to run any time you wish to be accepting connections.

    Quote Originally Posted by willemjar View Post
    should I still do server.close(); (I believe yes. was checking with server.isClosed())
    When you are done accepting connections, yes

    The posted code is very lengthy, and I have not attempted to filter through all of it. Copy paste existing functional code from a tutorial, which is what I did suggest multiple times, and even included links to tutorials and code.

  13. #13
    Member
    Join Date
    Jun 2013
    Posts
    61
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: a private chat application in process

    I have gone over everything, and thanks for you answering me consequently!
    I copied the while loop too!

    But here is what happens:
    1) the server socket waits and gets a incoming request than -> socket = server.accept(); and server.close();
    2) the application calls out two client than -> server.close(); and socket = new Socket(ip, port);

    So in either situation I should close server, right?

    Is the while loop really needed?
    could one not simply say: socket = server.accept(); and server.close();
    when 1) incoming call 2) calling out with socket?
    Since "while" is a loop and socket = server.accept(); is (more or the less) another loop?

  14. #14
    Member
    Join Date
    Jun 2013
    Posts
    61
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: a private chat application in process

    This thread is not going anywhere.....
    The program I wrote has some interesting problems but nobody is
    really going over the code seriously!! I understand because it is too long
    and not (still) very well written....
    But how are we going to learn (most suggestions of you jps had little to do with
    the real problems of the code). Understand me well jps this is not mend as a
    criticism of you. I am simply saying this is not working (I spend many, many hours
    programming and reading (your) suggestions).

    I know that simple things like asking "how to parse such to so" works out just fine, but
    what about with all the complicated and extended stuff?


    So I decided to write a small command line app that addresses the essence of the
    PrivateChat idea (maybe I should have started like that right away?). see next small code fragment
    and try it out!

    I tried it on single comp using the port 1501 and local host address and it worked just fine.

    But what happens trying it on two comp with to different IP: would that work too?
    (still figuring out how to use command line arg stuff out side the Neatbeans platform, yes
    these are the problems of a person with no comp science education):
    comp 1) input portnumber
    comp 2) input portnumber and IP of 1)

    WOULD THAT WORK? THEORETICALLY IT SHOULD, RIGHT?



    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
     
    /**
     *
     * @author willem
     *
     */
    public class Main {
        private static int port;
        private static String ip;
     
     
    public static void main(String[] args)  {
          System.out.println(" The applications waits for 0ne/ two commandline arg ");
          System.out.println(" 1) PORTNUMBER when waiting/ receiving request");
          System.out.println(" 2) PORTNUMBER and IP ADDRESS to calling out to the receiver");
          System.out.println(" when testing on one single machine: 1) 1501 /2) 1501 127.0.0.1" );
     
          try   {
             if (args.length == 1) {
     
                   port = Integer.parseInt(args[0]);
                   ServerSocket server = new ServerSocket(port);
                   System.out.println(" waiting for income request ");
                   Socket socket =  server.accept(); // handle the connection here
                   server.close();
                   System.out.println(" server closed ");
                   BufferedReader socketin = new BufferedReader (new
                                    InputStreamReader(socket.getInputStream()));
                   String linein;
                       while ((linein = socketin.readLine()) != null) {
                            System.out.println(linein); // printing the received line
                       }
             }
             else
             if (args.length == 2) {
                   port = Integer.parseInt(args[0]);
                   ip = args[1];
                   Socket socket = new Socket(ip, port);
                   socket.setSoTimeout(5000); // time out after 5 seconds
                   System.out.println(" sending out on port: " + port);
                   System.out.println(" ip " + ip);
                   System.out.println("sending: You say hello and I say goodbye");
                   PrintWriter socketout = new PrintWriter // sending out one single line
                            (socket.getOutputStream(), true /*autoFlush */);
                   socketout.println("receiving: You say hello and I say goodbye ");
                   socket.close();
                   System.out.println(" socket closed ");
             }
             else System.out.println(" error of arg input (arg<1 or arg>2) ");
          }
          catch (Exception e)  {
             e.printStackTrace();
          }
       }
    }

  15. #15
    Member
    Join Date
    Jun 2013
    Posts
    61
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: a private chat application in process

    The small program works perfect on one machine through local host address.
    But when running on two different machines (and using the wifi of my neighbours)
    there is a problem! So here is what I do:

    1) Comp 1, start the application on terminal with one arg 1501 (portnumber)
    and get the text "waiting for income request" on the terminal, good!
    2) read out the IP of Comp 1 through google "my IP" (is that all right?????)
    3) start Comp 2 with two arguments 1501 and the IP of Comp 1
    and do NOT get the text " sending out on port: etc."
    so it gets stuck on: Socket socket = new Socket(ip, port);
    and after some time I get an exception "operation timed out"
    (the comp 1 is waiting forever)

    what does this indicate?

  16. #16
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: a private chat application in process

    Quote Originally Posted by willemjar View Post
    I understand because it is too long
    and not (still) very well written....
    The long part is somewhat of an issue, but not the reason no one provided a solution


    Quote Originally Posted by willemjar View Post
    But how are we going to learn
    ...
    So I decided to write a small command line app that addresses the essence of the
    PrivateChat idea (maybe I should have started like that right away?).
    Q & A.


    Quote Originally Posted by willemjar View Post
    see next small code fragment
    and try it out!
    But what happens trying it on two comp with to different IP: would that work too?
    WOULD THAT WORK? THEORETICALLY IT SHOULD, RIGHT?
    This is somewhat of an issue. Who has the time? You try it out. You try it on two different computers. You tell us what happened. You tell us what should happen.

    When there are many examples of functional code available, it just does not warrant filtering through code containing all of the GUI components, add-ons, and accessories that may be present in a lengthy code such as the first sample. Best you start with a small "undecorated" -functional- application, and build on it. (like those readily available in tutorials)

    --- Update ---

    Having looked at the code in post#14, I can see you are still opening a server socket on both machines. Each machine (specifically the clients) do not need a ServerSocket at all. One ServerSocket on the server to establish a socket-to-socket between the server and client.

  17. #17
    Member
    Join Date
    Jun 2013
    Posts
    61
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: a private chat application in process

    "you are still opening a server socket on both machines."
    No not true, it depends on the number of arg, when only port number, it opens
    the server, but when port number and ip, it will open only the socket!
    The above situation is the only way that communicates will be established!

    But why is it not working on two machines with real IP (not the local one)?

    --- Update ---

    What is really weird jps is that when you type in google "my ip", you'll get it right away!
    But you can not find one working code in java accomplishing the same....
    (believe me I scanned over many and many)
    So what is going one here?

  18. #18
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: a private chat application in process

    Quote Originally Posted by willemjar View Post
    No not true, it depends on the number of arg, when only port number, it opens
    Yes you are right. I never looked past opening the server socket.. I made an assumption and jumped to a conclusion I should not have. I will have a look when I return

  19. #19
    Member
    Join Date
    Jun 2013
    Posts
    61
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: a private chat application in process

    Thanks, jps, but the question stays, the application is working correctly but not making
    a internet connection over an ip, so what am i missing?

  20. #20
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: a private chat application in process

    Quote Originally Posted by willemjar View Post
    Thanks, jps, but the question stays
    Yea, I understand. RL happens for me too and sometimes duty calls.
    Perhaps you are being blocked by a firewall or your internet provider. I do not see a problem.

  21. #21
    Member
    Join Date
    Jun 2013
    Posts
    61
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: a private chat application in process

    I have the application (finally) going and will print the code for whoever wants to try it out.
    But there is one more problem.
    The inner class that deals with the socket connections (one server and one normal socket) extends Thread.
    So two objects of the class are created:
    -sc1 which waits for incoming calls (server socket)
    -sc2 which calls out to (the server socket) through a new created socket!

    -When one only waits for calls the sc2 gets never created, but
    -when calling out, the server socket closes and the thread gets out of use, right!

    So what would I do after closing the server socket, that waits, and is the only
    thing that, that object sc1 does?

    sc1.interrupt ???

    if (cmd.equals("CONNECT")) {
     
                    // start the outgoing call constructor
                        sc2 = new SocketConnection(ipOut.getText(), port);     
                        sc1.closeConnection();
                        sc1.interrupt();      
                }


    --- Update ---

    The chat works when opening on one computer and using the local address.
    When using it for real there are still issues with firewalls etc.
    Who wants to help to fix that feel free to get involved!


    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
     
    package privatechat;
     
     
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.ComponentOrientation;
    import java.awt.Container;
    import java.awt.FlowLayout;
    import java.awt.Font;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.Inet4Address;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    import javax.swing.event.MenuEvent;
     
    /**
     *
     * @author willem
     * This private chat application shows your IP and waits,
     * through a socket connect loop, for the peer chatter to contact you.
     * When given the correct peer IP and by pushing "connect" the wait-loop
     * breaks off and a new socket connection starts to connect with the peer chatter.
     * After the proper handshake the receiver/ info text-area invites you
     * to send a greeting (or prints an error when the connections did not work out)
     * and the chat may begin (or not)!
     *
     */
    public class Main extends JFrame { // the main class sets the GUI and the listeners
        private Color bluecolor, blackcolor, redcolor;
        private Font theFont;
        private int port;
        private JTextField ipIn, ipOut;
        private JButton send, connect, save;
        private JComboBox scriptBox;
        private JTextArea textIn, textOut;
        private JLabel ipInLabel, ipOutLabel, scriptLabel, incomeChat, outcomeChat;
        private JCheckBoxMenuItem checkbmenu1;
        private ActionListener menuListener;
        private ActionListener panelListener;
        private SocketConnection sc1, sc2;
        private enum SocketState {LISTENING, ME_CONNECTING}
        private SocketState state;
        private String handshake, ip;
        private boolean listen;
        private static int threadcount = 0;
     
     
        public Main() {
     
                bluecolor = Color.BLUE;
                redcolor = Color.RED;
                blackcolor = Color.BLACK;
                theFont = new Font("SansSerif", Font.PLAIN, 14);
                port = 1501;;
                handshake = "willemprivatechat";
                menuListener = new MenuListener();
                panelListener = new panelListener();
                addWindowListener(new WindowAdapter() {
     
                    public void windowClosed(WindowEvent evt) {
                    }
                });
                Container contentPane = getContentPane();
     
                contentPane.add(CreateGuiPanel());
                setJMenuBar(createMenubars());
                getIp();
                sc1 = new SocketConnection(port);
              //  testconnect();
     
        }
     
        public static void main(String[] args)  {
            JFrame frame = new Main();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setTitle("PRIVATE CHAT");
            frame.setBounds(300, 300, 700, 600);
            frame.setResizable(false);
            frame.setVisible(true);   
        }
     
        public void testconnect()  {
            try {
                Socket socket = new Socket("95.19.97.17", 1501); // 62.37.67.235
            } catch (UnknownHostException ex) {
                textIn.append(" error in host connection \n" + ex);
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                textIn.append(" i/o error of connection \n" + ex);
            }
        }
     
     
        public JPanel CreateGuiPanel()  { // all the GUI for the chat panel
            // three buttons: connect, send, and save the text
            send = new JButton("send");
            send.setActionCommand("SEND");
            send.addActionListener(panelListener);
            connect = new JButton("connect");
            connect.setActionCommand("CONNECT");
            connect.addActionListener(panelListener);
            save = new JButton("save all the chat text");
            save.setActionCommand("SAVE");
            save.addActionListener(panelListener);
     
            //the text labels for the components
            ipInLabel = new JLabel ("My IP address    ");
            ipOutLabel = new JLabel("Peer's IP address");
            scriptLabel = new JLabel("Enscript the chat");
     
            // two IP textfields
            ipIn = new JTextField(12);
            ipIn.setText("");
            ipIn.requestFocusInWindow();
            ipIn.setMaximumSize(ipIn.getPreferredSize());
            ipInLabel.setLabelFor(ipIn);
            ipIn.setEditable(false);
            ipOut = new JTextField(12);
            ipOut.setText("127.0.0.1");
            ipOut.requestFocusInWindow();
            ipOut.setMaximumSize(ipIn.getPreferredSize());
            ipOutLabel.setLabelFor(ipOut);
            ipOut.setEditable(true);
     
            // two chat text field/ area
     
            textIn = new JTextArea(20,55);
            textIn.setLineWrap(true);
            textIn.setWrapStyleWord(true);
        //    textIn.setPreferredSize(new Dimension(30,10));
            textIn.setText("The Private Chat Application\n"
                             + "is waiting to get connected.\n"
                             + "when you know your peer's IP\n"
                             + "write it into the box and push\n"
                             + "connect and have fun.\n \n");
            textIn.setFont(new Font("Serif", Font.ITALIC, 16));
            textIn.setEditable(true);
            textOut = new JTextArea(4,50);
            textOut.setLineWrap(true);
            textOut.setWrapStyleWord(true);
        //    textOut.setPreferredSize(new Dimension(200,30));
            textOut.setFont(new Font("Serif", Font.ITALIC, 16));
            textOut.setEditable(true);
     
            JScrollPane scrollPanel1 = new JScrollPane(textIn);
            JScrollPane scrollPanel2 = new JScrollPane(textOut);
     
            //the enscript combo box
            String[] scriptitems = {"No Script"};
            scriptBox = new JComboBox(scriptitems);
            scriptBox.setSelectedIndex(0);
            scriptBox.addActionListener(menuListener);
            scriptBox.setActionCommand("COMBO");
     
            //the panel setups and named borders
            JPanel mainPanel = new JPanel(new BorderLayout());
     
            JPanel southPanel = new JPanel(new GridLayout(2, 1));
            JPanel centerPanel = new JPanel(new FlowLayout(FlowLayout.CENTER,3,3));
            JPanel northPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
     
            JPanel northbuttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
            JPanel southbuttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
            JPanel fieldPanel = new JPanel(new GridLayout(2, 1));
            JPanel ipInPanel = new JPanel(new GridLayout(1, 2));
            JPanel ipOutPanel = new JPanel(new GridLayout(1, 2));
            JPanel buttonCombo = new JPanel(new FlowLayout(FlowLayout.RIGHT));
     
            JPanel textPanel = new JPanel(new GridLayout(2, 1));
     
     
            // the south panel
            ipInPanel.add(ipInLabel);
            ipInPanel.add(ipIn);
            ipOutPanel.add(ipOutLabel);
            ipOutPanel.add(ipOut);
     
            fieldPanel.add(ipInPanel);
            fieldPanel.add(ipOutPanel);
            southPanel.add(fieldPanel);
            buttonCombo.add(connect);
            buttonCombo.add(scriptBox);
            northPanel.add(fieldPanel);
            northPanel.add(buttonCombo);
     
            //the center panel
            centerPanel.setBackground(Color.WHITE);
            centerPanel.add(scrollPanel1);
     
            //the north panel
            JPanel textoutPanel = new JPanel(new FlowLayout());
            textoutPanel.add(scrollPanel2);
            textoutPanel.add(send);
            southbuttonPanel.add(save);
            southPanel.add(textoutPanel);
            southPanel.add( southbuttonPanel);
     
            // all of the chat panel
            mainPanel.add(centerPanel, BorderLayout.CENTER);
            mainPanel.add(northPanel, BorderLayout.NORTH);
            mainPanel.add(southPanel, BorderLayout.SOUTH);
     
     
            return mainPanel;
        }
     
        public JMenuBar createMenubars()  { // the menubar plus items (not working yet)
            JMenuBar menuBar = new JMenuBar();
            JMenu setup = new JMenu("More Options");
            checkbmenu1 = new JCheckBoxMenuItem("test");
     
            checkbmenu1.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
            checkbmenu1.setHorizontalAlignment(checkbmenu1.LEADING);
         //   menuItem1.setMnemonic(KeyEvent.VK_C);
            JCheckBoxMenuItem checkbmenu2 = new JCheckBoxMenuItem("select all");
     
            checkbmenu2.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
            checkbmenu2.setHorizontalAlignment(checkbmenu2.LEADING);
            JMenuItem menuItem1 = new JMenuItem("Handshake");
            JMenuItem menuItem2 = new JMenuItem("Set Port");
            JMenuItem menuItem3 = new JMenuItem("Send File");
            JMenuItem menuItem4 = new JMenuItem("Quit");
     
     
            menuItem1.addActionListener(menuListener);
            menuItem2.addActionListener(menuListener);
            menuItem3.addActionListener(menuListener);
            menuItem4.addActionListener(menuListener);
            checkbmenu1.addActionListener(menuListener);
            checkbmenu2.addActionListener(menuListener);
     
            setup.add(menuItem1);
            setup.add(menuItem2);
            setup.add(checkbmenu1);
            setup.add(checkbmenu2);
            setup.add(menuItem3);
            setup.add(menuItem4);
            menuBar.add(setup);
            return menuBar;
        }
     
       public synchronized void setThreadCount() {
           threadcount = threadcount + 1;
           System.out.println("ip count " + threadcount);
       }
     
       public synchronized int getThreadCount() {
           return threadcount;
       }
     
       public void getIp() {
            try {
                ipIn.setText(Inet4Address.getLocalHost().getHostAddress());
            } catch (UnknownHostException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
     
     
       class MenuListener implements ActionListener { // not working yet
     
                public void menuSelected(MenuEvent me) {
     
                }
     
                public void menuDeselected(MenuEvent me) {
     
                }
     
                public void menuCanceled(MenuEvent me) {
     
                }
     
            public void actionPerformed(ActionEvent ae) {
     
            }
       }
     
         class panelListener implements ActionListener {
     
     
            public void actionPerformed(ActionEvent e) {
                String cmd = e.getActionCommand();
     
     
                if (cmd.equals("CONNECT")) {
     
                    // start the outgoing call constructor
                        sc2 = new SocketConnection(ipOut.getText(), port);     
                        sc1.closeConnection();
                        sc1.interrupt();      
                }
                if (cmd.equals("SEND")) { // sends the chat message
                    String line = null;
                    line = textOut.getText();                
                    textIn.append("Me: " + line + "\n");
                    textOut.setText("");
     
                    if (state.equals(SocketState.LISTENING))
                    sc1.transmit().println(line + "\n");
     
                    if (state.equals(SocketState.ME_CONNECTING))
                    sc2.transmit().println(line + "\n");
     
                }
                if (cmd.equals("SAVE")) { // not working
                    System.out.println("save");
                }
            }
       }
     
      /**
     *
     * The second private inner class takes care of the socket connections.
     *
     *
     *
     */
     
     
        private class SocketConnection extends Thread {
            private int port;
            private String ip = null;
            private Socket socket;
            private ServerSocket server;
            PrintWriter socketout;
     
     
            public SocketConnection(int port)  {
                state = SocketState.LISTENING; // incoming/ waiting for caller
                listen = true;
                this.port = port;
                start();
                setThreadCount();
                System.out.println("first socket constructor");
            }
     
            public SocketConnection(String ip, int port)  {
                state = SocketState.ME_CONNECTING; // sending/ calling out to peer
                this.ip = ip;
                this.port = port;
                start();
                setThreadCount();
                System.out.println("second socket constructor");
            }
     
            public void run() {
     
                try {
                       /*  Here, waiting for the peer to connect.
                        *  When connected the waiting socket "server" shuts down.
                        *  Or the waiting-clause gets interrupted when the
                        *  application calls out to the peer through "connect".
                        *  For this action one needs the IP of the peer.
                        */
                    if (state.equals(SocketState.LISTENING))  {
     
                        server = new ServerSocket(port);
     
                        textIn.append("    listening to incoming calls, state " +
                                           state +  "\n" +
                                           " threadcount >>> " + getThreadCount() + "\n" +
                                           " portnumber " + port + "\n\n");
     
                              socket =  server.accept(); // handle the connection here
                              server.close();
                              textIn.append("   connecting to incoming call, state " +
                                     state +  "\n" +
                                    " threadcount >>> " + getThreadCount() + "\n" +
                                    "   is server closed >>> " + server.isClosed() + "\n" +
                                    "   socket >>>      " + socket + "\n" +                                
                                    "   port: " + port +  "\n\n");                    
                    }
                    else
                     /* From here, the application calls out.
                     * It is important to know that the same application
                     * waits for calls passively and calls out actively,
                     * depending on: if (state == SocketState.ME_CONNECTING){
                     *
                     */
                    if (state.equals(SocketState.ME_CONNECTING))  {
                        socket = new Socket(ip, port);
                        // socket.setSoTimeout(5000); // time out after 10 seconds
                        textIn.append("  calling out connecting to, state " +
                                state +  "\n" +
                                " ID " + ip + "\n" +
                                " port " + port +  "\n" +
                                " threadcount >>> " + getThreadCount() + "\n" +
                                "   server >>>      " + server + "\n" +
                                "   socket >>>      " + socket + "\n" + "\n\n");
                    }
                     /* From here on a connection is established, either
                     * passive or active and the chat routine of Me and Peer
                     * should begin.... or not.....
                     *
                     */
                 }
     
                 catch (IOException ex) {
     
                        textIn.append(" socket catch, state " + state + " > " +
                            " threadcount >>> " + getThreadCount() + "\n" +
                            " IP >>> " + ip + "\n" +
                            " port >>> " + port + "\n" +
                            " socket >>> " + socket + "\n" +
                            "   socket >>>      " + socket + "\n" +
                            ex + "\n\n");
                 }
     
                /* The reading and writing methods
                 * concerning the chat communication
                 * (reading and writing happens simultaneously)
                 *
                 */
                 if (socket != null)  {
                        try { // reading and sending text lines
     
                            textIn.append(" getting into buffer connection state  "  +
                               state + "\n" +
                               " threadcount >>> " + getThreadCount() + "\n" +
                               " socket >>> " + socket + "\n" +
                               " IP >>>     " + ip + "\n" +
                               " port >>>   " + port + "\n" +
                               "\n\n" );
                            String linein;
                            BufferedReader socketin = new BufferedReader (new
                                    InputStreamReader(socket.getInputStream()));
                            // the socketout is connected with the "send" button
                            // see at the buttom the transmite method!
                            socketout = new PrintWriter
                            (socket.getOutputStream(), true /*autoFlush */);
                            while ((linein = socketin.readLine()) != null) {
                                    if (!linein.equals(""))
                                    textIn.append("peer: " + linein + "\n");
     
                            }
                        }
     
                        catch(Exception e) {
                        textIn.append(" communication error, state " + state + " > " + e
                             + " socket " + socket +  "\n\n");
                        }
                        finally  {
                            closeConnection();
                        }
                }
                else textIn.append(" socket is null no communication \n\n");
     
    	} // end of the run method
     
            public boolean Handschake(String handshake, String hnd)  { // not working yet
                if (handshake.equals(hnd))
                return true;
                else
                return false;
            }
     
            public PrintWriter transmit()  { // communicating with the GUI main clase
                if (socketout == null)
                textIn.append(" The socked for transmission is null \n\n");
                return socketout;
            }
     
     
     
     
            public boolean Serverclossed() {
                return server.isClosed();
            }
     
     
            void closeConnection() { // close and clean up both sockets
                try {
     
                    if (server != null && !server.isClosed()) {
                         server.close();
                         textIn.append(" server socket closseddddddd " + "\n\n");
                    }
                    else
     
                    if (socket != null && !socket.isClosed()) {
                         socket.close();
                         textIn.append(" socket clossedddddddddd " + "\n\n");
                    }
                }
                catch (IOException ex) {
                     textIn.append(" error in clossing connections \n");
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex + "\n\n");
                }       
            }
     
     
        } // end of the inner class
     
    }

Similar Threads

  1. How can i create a chat application
    By Celestine in forum Java Theory & Questions
    Replies: 7
    Last Post: July 28th, 2013, 12:34 PM
  2. Chat application
    By Celestine in forum What's Wrong With My Code?
    Replies: 1
    Last Post: July 27th, 2013, 12:22 PM
  3. Chatting application in java (PUblic And private)
    By nakul dev in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 27th, 2012, 12:27 PM
  4. Start application, and return process ID (PID)
    By prepared91 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: April 26th, 2011, 03:06 AM