Search code examples
javaphpmultithreadingsocketssynchronize

Java: Synchronizing socket input


My first attempt at writing a client for a php socket server and I'm running into a little trouble and I'm sort of being flooded with info!

With the server, we want an open connection, I want my client end to wait until it receives data before notifying the thread to start parsing the input-stream. Is this achievable without using a loop? I'd rather be able to call lock.notify().

I was also looking at NIO, is this a viable option for what I want? Here's the code I have so far, but again, I'm just trying to avoid the for(;;) and maybe even queue the received messages as they will most likely just be JSON

 Thread serverRecieve = new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            for (;;) {
                if (in != null) {
                    String line;
                    while ((line = in.readLine()) != null) {
                        sout(line);
                    }
                } else {
                    sout("inputstream is null! Waiting for a second to test again");
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(WebManager.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(WebManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
});

Thanks guys! PS: I did look through A LOT of socket threads on here but decided it would be easier just to ask what I need.


Solution

  • I think you can use a while loop and put a condition using in != null as:

        while(in == null){
           //wait for a second before checking the in stream again
           try {
                sout("inputstream is null! Waiting for a second to test again");
                Thread.sleep(1000);
           } catch (InterruptedException ex) {
              Logger.getLogger(WebManager.class.getName()).log(Level.SEVERE, null, ex);
           }    
        }
    
         //now your in is available. Read the data and proceed
         String line = null;
         while ((line = in.readLine()) != null) {
              sout(line);
         }
    

    The first while loop will terminate as soon in stream is available.