Reputation: 440
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();
}
}
Upvotes: 1
Views: 682
Reputation: 1911
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.
Upvotes: 1