1

I use this code to run simple TCP Server by JAVA and I use Socket Protocol android application to be client. The problem is when the client connected then I send the message the Server side do nothing until I disconnected the client the massage appear after that. I think something stuck at while((inputLine = in.readLine()) != null)

import java.net.*;
import java.io.*;

public class TCPIP {

public static void main(String[] args) throws IOException {
    ServerSocket serverSocket = null;
    try{
        serverSocket = new ServerSocket(10007);
    }
    catch(IOException e)
    {
        System.err.println("Could not listen on port 10007");
        //System.exit(1);
    }
    Socket clientSocket = null;
    System.out.println("Waiting for connection....");

    try{
        clientSocket = serverSocket.accept();
    }
    catch(IOException e){
        System.err.println("Accept Failed");
        //System.exit(1);
    }
    System.out.println("Connection Successful");
    System.out.println("Waiting for input");

    PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true); 
    BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));


    String inputLine;


    while((inputLine = in.readLine()) != null) 
    {
        System.out.println("Server: "+ inputLine);
        out.println(inputLine);

        if(inputLine.equals("Bye."))
        {
            break;
        }
    }
    out.close(); 
    in.close(); 
    clientSocket.close(); 
    serverSocket.close(); 
}

}
4
  • 1
    Is your client actually sending a line? Commented Dec 30, 2014 at 13:35
  • Yes it is. Because I test this android app(my client) with c# socket before. Commented Dec 30, 2014 at 13:37
  • It needs to be more specific: a line ends with a newline. Probably the client is not sending a newline and so the readLine() method is still waiting for it. Commented Dec 30, 2014 at 13:42
  • I just forget to send newline! Thank you guys Commented Dec 30, 2014 at 14:08

1 Answer 1

1
while((inputLine = in.readLine()) != null)

is bad code, you should use

inputLine = in.readLine();
while(inputLine != null)
{
   inputLine = in.readLine();
}

instead. readLine() waits for the newline-character - make sure your server sends it or else your client will block until the connection is closed : https://docs.oracle.com/javase/6/docs/api/java/io/BufferedReader.html#readLine()

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.