Results 1 to 17 of 17
  1. #1
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default (forcing) closing a server socket and opening a (new) socket

    Who can help me out here?
    A good way of dealing with a server socket might be the next code fragment?
    -If a client connects the ServerSocket returns a (normal) socket and theServerSocket is closed, right!
    -But if nobody ever connects, the waiting goes on for ever!
    So what if I like to close the ServerSocket anyway, through pushing e.g
    an exit/ close button and provoking/ forcing a server.close() before a client connect?

    -Would that be a good programming costume or is there another way dealing with this situation?
    -When doing so (pls realize that there was no server.accept) why is the catch clause called? And why has that catch-call consequences for opening a new (normal) socket, immediately after closing the server socket
    (in concrete: the correctly opened new socket,
    after closing the server socket and having the catch clause,
    is consequently NULL and there is no way to get a stream!

    Java Code:
    public void run() { 	// of course running the connection wait loop in a thread?
    	try {
    		server = new ServerSocket(port); // port is of int
    		try {
                              socket =  server.accept(); 	// handle the connection here
                              server.close(); 			// close it after connecting
                              
                     }
                     catch (SocketTimeoutException e) {
                                 // handel or not handle?
                     }
    
            catch (IOException ex) {
    		 // handel or not handle?
            }
                
            
    }
    Last edited by willemjav; 08-08-2013 at 02:39 PM.

  2. #2
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: (forcing) closing a server socket and opening a (new) socket

    I realize some later that the catch (SocketTimeoutException e)
    is not really needed, right?
    So this code also goes:


    Java Code:
    public void run() {     // of course running the connection wait loop in a thread?
        try {
                  server = new ServerSocket(port); // port is of int
                  socket =  server.accept();    // handle the connection here
                  server.close();           // close it after connecting
    
        catch (IOException ex) {
             // handel or not handle?
        }
                 
       
    }
    Last edited by willemjav; 08-08-2013 at 02:40 PM.

  3. #3
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: (forcing) closing a server socket and opening a (new) socket

    by taking out catch (SocketTimeoutException e)
    I got rid of the null pointer of the socket, great!

    But there is still another problem.

    when talking through the established socket from a java chat application to
    terminal (telnet) over the local address: 127.0.0.1
    The communication only works in one direction (from telnet to java chat)!

    here is the responsible code block:

    Java Code:
    if (socket != null)  {
                        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) {
                                    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");

    and:

    Java Code:
     public PrintWriter transmit()  { // communicating with the GUI main clase     
                return socketout;
            }
    the send button of the GUI class:

    Java Code:
       if (cmd.equals("SEND")) { // sends the chat message
                    String line = null;
                    line = textOut.getText();                
                    textIn.append("Me: " + line + "\n");
                    textOut.setText("");
                    sc2.transmit().println(line + "\n");  // text send out of chat
     }
    (sc2 is the thread object where the sockets etc. are established)
    Last edited by willemjav; 08-08-2013 at 03:38 PM.

  4. #4
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: (forcing) closing a server socket and opening a (new) socket

    When pushing send button get the following error:


    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at privatechat.Main$panelListener.actionPerformed(Mai n.java:347)
    at javax.swing.AbstractButton.fireActionPerformed(Abs tractButton.java:2028)
    at javax.swing.AbstractButton$Handler.actionPerformed (AbstractButton.java:2351)
    at javax.swing.DefaultButtonModel.fireActionPerformed (DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultB uttonModel.java:242)
    at javax.swing.plaf.basic.BasicButtonListener.mouseRe leased(BasicButtonListener.java:236)
    at java.awt.Component.processMouseEvent(Component.jav a:6382)
    at javax.swing.JComponent.processMouseEvent(JComponen t.java:3275)
    at java.awt.Component.processEvent(Component.java:614 7)
    at java.awt.Container.processEvent(Container.java:208 3)
    at java.awt.Component.dispatchEventImpl(Component.jav a:4744)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2141)
    at java.awt.Component.dispatchEvent(Component.java:45 72)
    at java.awt.LightweightDispatcher.retargetMouseEvent( Container.java:4619)
    at java.awt.LightweightDispatcher.processMouseEvent(C ontainer.java:4280)
    at java.awt.LightweightDispatcher.dispatchEvent(Conta iner.java:4210)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2127)
    at java.awt.Window.dispatchEventImpl(Window.java:2489 )
    at java.awt.Component.dispatchEvent(Component.java:45 72)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.j ava:710)
    at java.awt.EventQueue.access$400(EventQueue.java:82)
    at java.awt.EventQueue$2.run(EventQueue.java:669)
    at java.awt.EventQueue$2.run(EventQueue.java:667)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectio nPrivilege(AccessControlContext.java:87)
    at java.security.AccessControlContext$1.doIntersectio nPrivilege(AccessControlContext.java:98)
    at java.awt.EventQueue$3.run(EventQueue.java:683)
    at java.awt.EventQueue$3.run(EventQueue.java:681)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectio nPrivilege(AccessControlContext.java:87)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java: 680)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(EventDispatchThread.java:296)
    at java.awt.EventDispatchThread.pumpEventsForFilter(E ventDispatchThread.java:211)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:196)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:188)
    at java.awt.EventDispatchThread.run(EventDispatchThre ad.java:122)

  5. #5
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,256
    Rep Power
    6

    Default Re: (forcing) closing a server socket and opening a (new) socket

    You're having a whole discussion with yourself! I can't comment on your socket logic because I don't even understand what you're functionally trying to achieve, but your last error is quite simple:

    Main.java:347

    What object reference variable on line 347 of your main class is null and shouldn't be?
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  6. #6
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: (forcing) closing a server socket and opening a (new) socket

    Yes,, erik I usually talk to myself at java blogs.... funny he?
    the line 347 is: sc2.transmit().println(line + "\n");
    of the above transmit() method, does that make since?

  7. #7
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,256
    Rep Power
    6

    Default Re: (forcing) closing a server socket and opening a (new) socket

    does it make sense to you because you have to fix it.

    Simple reasoning:

    - either sc2 is null
    - or what transmit() returns is null

    Now you have to figure out what is true. My money is on the second case.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  8. #8
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: (forcing) closing a server socket and opening a (new) socket

    here is the whole run method of an application which is called "private chat" (which I like to encrypt some later)

    Java Code:
    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

  9. #9
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: (forcing) closing a server socket and opening a (new) socket

    -the sc2 is NOT NULL for sure!
    -so the socketout should be NULL, right?

    the socketout is created by:
    socketout = new PrintWriter
    (socket.getOutputStream(), true /*autoFlush */);

    - so that means the socket is NULL, right?

    But since the BufferedReader, based on the same socket, works.....

    So what is going on here?

    (or maybe the getOutputStream() is NOT responding?)

    No the socketout is not NULL: java.io.PrintWriter@301db5ec
    Last edited by willemjav; 08-08-2013 at 04:06 PM.

  10. #10
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,256
    Rep Power
    6

    Default Re: (forcing) closing a server socket and opening a (new) socket

    SOMETHING is null, so keep looking. Java does not lie to you.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  11. #11
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: (forcing) closing a server socket and opening a (new) socket

    What if java is not as logic as it should be.....
    Now you understand why at the end I am talking only to myself?

  12. #12
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,256
    Rep Power
    6

    Default Re: (forcing) closing a server socket and opening a (new) socket

    Well if that were true you are stuck and should go use something else, because if the tools you're using don't make sense then there is simply no solution.

    Yeah I'm really ducking out of this thread now. Good luck finding the mistake in the Java API.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  13. #13
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: (forcing) closing a server socket and opening a (new) socket

    thanks, un saludo erik

  14. #14
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: (forcing) closing a server socket and opening a (new) socket

    You, erik, and java are right
    the sc2 object: null
    so let see how that can happen.......

  15. #15
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,256
    Rep Power
    6

    Default Re: (forcing) closing a server socket and opening a (new) socket

    Being right is not going to make me feel better. I will only be happy when you yourself realize just how wrong your earlier "What if java is not as logic as it should be" is. You just don't get anywhere making claims like that, you have to assume you yourself are making a mistake. Otherwise you're just making excuses to not have to look any more.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  16. #16
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: (forcing) closing a server socket and opening a (new) socket

    So there are two thread objects created:
    for incoming calls: sc1
    for calling out: sc2

    The read/ write part is the same for both objects
    -when the application waits for calls, the second thread
    is not created!
    so when calling out, it creates the second thread object sc2
    and I stop the first thread, like this:
    sc1.interrupt();

    is that all right so?

    The next correction takes care of the error (again thanks and nice talking to you
    erik)
    Java Code:
    if (sc1 == null)
                    sc2.transmit().println(line + "\n");  // text send out of chat
                    else
                    sc1.transmit().println(line + "\n");  // text send out of chat

  17. #17
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: (forcing) closing a server socket and opening a (new) socket

    That code did not work very well

    so here is a better version:


    if (state.equals(SocketState.LISTENING))
    sc1.transmit().println(line + "\n");

    if (state.equals(SocketState.ME_CONNECTING))
    sc2.transmit().println(line + "\n");

Similar Threads

  1. Socket Programming ERROR : Socket not connected
    By vishrut_n_shah in forum Networking
    Replies: 0
    Last Post: 11-04-2011, 10:32 AM
  2. Replies: 1
    Last Post: 07-02-2010, 02:18 PM
  3. Writing to Socket outputStream w/o closing it
    By eyal in forum Networking
    Replies: 6
    Last Post: 05-17-2010, 05:26 PM
  4. append response to the request from Socket and write to another socket
    By vaibhav_singh_vs@yahoo.co in forum Networking
    Replies: 3
    Last Post: 04-17-2009, 08:02 PM
  5. Replies: 3
    Last Post: 01-26-2009, 06:30 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •