14 Replies Latest reply: May 19, 2011 3:16 AM by 862937 RSS

    Streams and threads closing

    862937
      I'm doing this project for college and I'm having lots of errors, specially with streams and threads. Here, I will post my code if you see something wrong let me know
      public void run() {       
                try {
                     ss = new ServerSocket(9999);
                     while(true){
                     areaChat.append("\n(Server):Escuchando");
                     s = ss.accept();
                     InetAddress addr = s.getInetAddress();
                     ip = addr.getHostAddress();
                     na = addr.getHostName();
                     areaChat.append("\n(Server): Bienvenido cliente "+na+" usted se ha conectado desde: "+ ip);
                     this.writeLine("Bienvenido cliente "+na+" usted se ha conectado desde: "+ ip);
                     nwc c = new nwc();
                     Thread t = new Thread(c);
                     t.start();
                     //t.interrupt();
                }     
                } catch (IOException e) {
                     closeServer();
                     e.printStackTrace();
                     }
        }     
           
        public void writeLine(String line){
                try{
                     if (line!=null){
                     oos.writeObject(line);
                     areaChat.append(" \n(Server): "+line);
                     }
                }catch(Exception ex){
                     ex.printStackTrace();
                }
           }
           
           public void readLine(){
                try{
                     while(true){
                          Object aux = ois.readObject();
                          if(aux!=null && aux instanceof String)
                               areaChat.append("\nCliente: "+(String)aux);
                               String v=aux.toString(); 
                               if (v.equals("poll results")){
                                    this.writeLine("1."+sendresults(0));
                                    this.writeLine("2."+sendresults(1));
                               }else{
                                    String vaux=v;
                                    score(v,vaux);
                                   Thread.sleep(20);
                               }
                     }          
                }catch(Exception ex){
                     ex.printStackTrace();
                }
           }
           
           public void closeServer(){
                try{
                     oos.close();
                     ois.close();
                     s.close();
                     ss.close();
                }catch(Exception ex){
                     ex.printStackTrace();
                }
           }
                
           public class nwc implements Runnable {
                
                public void run() {
                       try {
                          oos = new ObjectOutputStream(s.getOutputStream());
                          ois = new ObjectInputStream(s.getInputStream());
                          readLine();
                     } catch (IOException e) {
                          e.printStackTrace();
                                       closeServer();
                     }          
                }  
           }
      this is the server, if you give me some hints about what I'm doing wrong, I might be able to correct the client for my self

      the project is about a poll a it is supossed to be concurrent and this is. But I'm having problems with the threads and the streams( when to open, close these objects) Would you help me ? . I appreciate a lot any kind of help or hint.;

      I will post the error codes in a minute.

      Edited by: 859934 on May 18, 2011 6:48 PM

      Edited by: 859934 on May 18, 2011 7:29 PM
        • 1. Re: Found the error!
          796440
          859934 wrote:
          I'm doing this project for college and I'm having lots of errors, specially with streams and threads.
          Copy/paste the exact, complete error messages, and indicate clearly which lines are causing them. (Note that your line numbers mean nothing here.)
          But I'm having problems with the threads and the streams.
          You'll have to be a lot more specific than that.

          Edited by: jverd on May 18, 2011 7:23 PM
          • 2. Re: Found the error!
            EJP
            But I'm having problems with the threads and the streams.
            You'll have to be a lot more specific than that.
            Agreed. But I'll give you one hint: don't do any I/O in the accept loop. Just accept sockets and start threads. Do the I/O in the thread, that's what it's for. And another hint: you don't need ObjectInput/OutputStreams just to read & write lines. Use a BufferedReader and a BufferedWriter.
            • 3. Re: Streams and threads closing
              862937
              these are the error codes i'm getting..
               java.lang.NullPointerException
                   at MultiThreadServer.writeLine(MultiThreadServer.java:102)
                   at MultiThreadServer.run(MultiThreadServer.java:87)
                   at java.lang.Thread.run(Thread.java:662)
              Conexion Exitosa
              java.io.EOFException
                   at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2553)
                   at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1296)
                   at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350)
                   at MultiThreadServer.readLine(MultiThreadServer.java:113)
                   at MultiThreadServer$nwc.run(MultiThreadServer.java:221)
                   at java.lang.Thread.run(Thread.java:662)
              java.net.SocketException: Socket closed
                   at java.net.SocketInputStream.socketRead0(Native Method)
                   at java.net.SocketInputStream.read(SocketInputStream.java:129)
                   at java.net.SocketInputStream.read(SocketInputStream.java:182)
                   at java.io.ObjectInputStream$PeekInputStream.peek(ObjectInputStream.java:2248)
                   at java.io.ObjectInputStream$BlockDataInputStream.peek(ObjectInputStream.java:2541)
                   at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2551)
                   at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1296)
                   at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350)
                   at EchoClient.readLine(EchoClient.java:141)
                   at EchoClient.run(EchoClient.java:112)
                   at java.lang.Thread.run(Thread.java:662)
              java.lang.NullPointerException
                   at MultiThreadServer.closeServer(MultiThreadServer.java:206)
                   at MultiThreadServer.run(MultiThreadServer.java:94)
                   at java.lang.Thread.run(Thread.java:662)
              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 MultiThreadServer.run(MultiThreadServer.java:79)
                   at java.lang.Thread.run(Thread.java:662)
              java.lang.NullPointerException
                   at MultiThreadServer.closeServer(MultiThreadServer.java:206)
                   at MultiThreadServer.windowClosed(MultiThreadServer.java:232)
                   at java.awt.AWTEventMulticaster.windowClosed(AWTEventMulticaster.java:342)
                   at java.awt.Window.processWindowEvent(Window.java:1868)
                   at javax.swing.JFrame.processWindowEvent(JFrame.java:274)
                   at java.awt.Window.processEvent(Window.java:1823)
                   at java.awt.Component.dispatchEventImpl(Component.java:4652)
                   at java.awt.Container.dispatchEventImpl(Container.java:2099)
                   at java.awt.Window.dispatchEventImpl(Window.java:2478)
                   at java.awt.Component.dispatchEvent(Component.java:4482)
                   at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:644)
                   at java.awt.EventQueue.access$000(EventQueue.java:85)
                   at java.awt.EventQueue$1.run(EventQueue.java:603)
                   at java.awt.EventQueue$1.run(EventQueue.java:601)
                   at java.security.AccessController.doPrivileged(Native Method)
                   at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
                   at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
                   at java.awt.EventQueue$2.run(EventQueue.java:617)
                   at java.awt.EventQueue$2.run(EventQueue.java:615)
                   at java.security.AccessController.doPrivileged(Native Method)
                   at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
                   at java.awt.EventQueue.dispatchEvent(EventQueue.java:614)
                   at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
                   at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
                   at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
                   at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
                   at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
                   at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
              • 4. Re: Streams and threads closing
                EJP
                java.net.SocketException: Socket closed
                That means you closed the socket, or its input stream or output stream. That could happen because of not following my first piece above, so you have I/O code all over the place.
                • 5. Re: Found the error!
                  862937
                  But im doing the i/o in the thread ... dont you see it? or im not seeing it?
                  • 6. Re: Streams and threads closing
                    862937
                    EJP I don't get your advice, Would you exemplify it for me?
                    • 7. Re: Streams and threads closing
                      EJP
                                     InetAddress addr = s.getInetAddress();
                                     ip = addr.getHostAddress();
                                     na = addr.getHostName();
                      These are all DNS operations. They involve I/O.
                                     areaChat.append("\n(Server): Bienvenido cliente "+na+" usted se ha conectado desde: "+ ip);
                      This looks like a Swing operation that should be done in the AWT thread.
                                     this.writeLine("Bienvenido cliente "+na+" usted se ha conectado desde: "+ ip);
                      This is I/O.
                                     //t.interrupt();
                      Don't just comment out your garbage. Delete it.
                                } catch (IOException e) {
                                     closeServer();
                                     e.printStackTrace();
                      I would do those in the opposite order. You want to know about the exception first.
                                                   Thread.sleep(20);
                      This is pointless. The read will block until there is something to read. This just wastes more time. Remove it.
                                     oos.close();
                                     ois.close();
                                     s.close();
                      If 'oos' and 'ois' belong to 's', you only need to close 'oos'. The others are closed automatically.
                                public void run() {
                                       try {
                                          oos = new ObjectOutputStream(s.getOutputStream());
                                          ois = new ObjectInputStream(s.getInputStream());
                                          readLine();
                                     } catch (IOException e) {
                                          e.printStackTrace();
                      closeServer();
                                     }          
                                }  
                           }
                      This is the thread code. This is where all the I/O related to that socket should be done. Move it here.
                      • 8. Re: Streams and threads closing
                        862937
                        Wow thanks a lot EJP , I didn't know that.

                        Nevertheless the program keeps sending errors in the same part
                        Now I'm getting these new errors
                        java.io.StreamCorruptedException: invalid type code: 00
                             at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1355)
                             at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350)
                             at MultiThreadServer.readLine(MultiThreadServer.java:108)
                             at MultiThreadServer$nwc.run(MultiThreadServer.java:218)
                             at java.lang.Thread.run(Thread.java:662)
                        
                        java.io.StreamCorruptedException: invalid type code: 00
                             at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1355)
                             at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350)
                             at MultiThreadServer.readLine(MultiThreadServer.java:108)
                             at MultiThreadServer$nwc.run(MultiThreadServer.java:218)
                             at java.lang.Thread.run(Thread.java:662)
                        Im pretty sure that it is related to the ois.readObject(), but I dont know the reason of this erros, do you have a clue?
                        • 9. Re: Streams and threads closing
                          DrClap
                          859934 wrote:
                          Im pretty sure that it is related to the ois.readObject(), but I dont know the reason of this erros, do you have a clue?
                          Yes, you are correct. It's most likely because you aren't sending an object but you are trying to receive an object, or something like that. But as EJP already said:
                          And another hint: you don't need ObjectInput/OutputStreams just to read & write lines. Use a BufferedReader and a BufferedWriter.
                          I would take that hint if I were you.
                          • 10. Re: Streams and threads closing
                            862937
                            Hello DrClap, thanks for your advice! I don't want to be stubborn but I my knowledge about this specific area of Java is even smaller (which is hardly possible) than other areas. How should I use those tools? (buffered readers / writers )

                            Edited by: 859934 on May 18, 2011 9:35 PM
                            • 11. Re: Streams and threads closing
                              EJP
                              java.io.StreamCorruptedException: invalid type code: 00
                                   at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1355)
                              That's one of the classes I told you not to use. So don't use it.
                              How should I use those tools? (buffered readers / writers)
                              They aren't tools, they are classes, and I gave you the correct names, and the answer to this question is in their Javadoc, which is the first thing you should have looked at.
                              • 12. Re: Streams and threads closing
                                862937
                                Well it is 3:18 am in the morning and I've implemented the bufferederReader and the printwriter classes. I got rid of a lot of a errors, but I'm having an error and I hope you could help me whit it.

                                As I've told you before this project is about a poll , I would like you to check it out and try to find/fix the issue you can download the project http://www.2shared.com/file/bCowJEIO/asdsad.html ... it wont work at least you have the files in your project folder.

                                the error occurs when you open 2 clients or more at the same time, if you open new clients the only client that will be able to fully vote will be the last client opened, the rest of the clients will vote just for the 1st place ( I don't know why this is happening, here I need your help )
                                To see the error I've told you about you have to run a server and two clients (at least), then you will vote with the first client you opened, after you will vote with the second client and you will get the error explained above. note: you can do this with more clients and only the last client opened will be able to fully vote.

                                I know its pretty ugly and its not validated but I'll add those features later on :)

                                Thanks a lot guys, especially EJP you have been really kind.

                                Edited by: 859934 on May 19, 2011 12:47 AM
                                • 13. Re: Streams and threads closing
                                  EJP
                                  I would like you to check it out and try to find/fix the issue you can download the project
                                  No way in the wide world whatsoever. This is a forum not a programming or debugging service. I will read whatever short bits of code you post here and comment. If you want to hire me see my Web page.
                                  the error occurs
                                  The error you described was a java.io.StreamCorruptedException, which is related only to ObjectInput/OutputStreams. As you're not using them any more, you cannot possibly* be still getting that error. You will have to break down and tell us what error you are getting now, including a full stack trace and the surrounding code and an indication of which line the exception is being thrown from. In a short readable sample of the code.
                                  • 14. Re: Streams and threads closing
                                    862937
                                    I should 've expected that response , that wasn't a cool request from me. thank a lot man you helped me out a ton.