This discussion is archived
3 Replies Latest reply: Oct 11, 2009 4:11 PM by EJP RSS

ServerSocket - send info to client

843789 Newbie
Currently Being Moderated
Here is what I'm trying to do:
Client will connect to my Java and send some data to the server.
The server will process the data and sends something back to the client.
           ServerSocket insocket = new ServerSocket(27016);

            while (true) {
                Socket accepted = insocket.accept();

                BufferedReader br = new BufferedReader(new InputStreamReader(accepted.getInputStream()));
                PrintWriter out = new PrintWriter(accepted.getOutputStream(), true);

                 out.println("Client receives this WELCOME MESSAGE");
                String line = br.readLine();
                while (line != null && accepted.isConnected()) {

                    System.out.println(line); // this line is NEVER null the first time, so the loop runs at least once!
                    out.println("THIS MESSAGE NEVER REACHES THE CLIENT");

                    line = br.readLine();
                }
               

            }
my client code is in PHP but i'm sure there is nothing wrong with it

$fp = fsockopen("something.com", 27016, $errno, $errstr, 10);
fputs ($fp, "process this string"); //send data to server
echo fgets($fp, 1024); // read data sent from the server. So far it only receives the welcome message and not the messages inside the while loop
  • 1. Re: ServerSocket - send info to client
    gimbal2 Guru
    Currently Being Moderated
    is that all the PHP script code? I'd imagine that the reading code would also be in a while loop there.
  • 2. Re: ServerSocket - send info to client
    r035198x Pro
    Currently Being Moderated
    >
    ; // read data sent from the server. So far it only receives the welcome message and not the messages inside the while loop
    Did you check to see if
    line != null && accepted.isConnected()
    returned true or false?
  • 3. Re: ServerSocket - send info to client
    EJP Guru
    Currently Being Moderated
    String line = br.readLine();
    That reads a line terminated by a line terminator.
    while (line != null && accepted.isConnected()) {
    The null test means end-of-stream. The test for Socket.isConnected() is pointless, as it will return true at this point, and will continue to do so forever. It tells you what you have done to the socket, not what is the state of the connection. The null would tell you about EOS, and an IOException would tell you about any other problem.
    fputs ($fp, "process this string"); //send data to server
    That puts a string without a line terminator.

    So the readLine() method will keep blocking waiting for the line terminator.