I’m trying to read data from socket using threading run method:
@Override
public void run() {
while(true){
try{
String o = "";
socketServer = new ServerSocket(port);
System.out.println("Waiting for connection on port "+port+".");
Socket socket = new Socket();
socket = socketServer.accept();
System.out.println("Connection got.");
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
int c;
while(( c = input.read()) != -1)
o += (char)c;
PrintWriter output = new PrintWriter(socket.getOutputStream());
output.println("ok");
output.flush();
output.close();
input.close();
socket.close();
socketServer.close();
textFieldMessage.setText("Сообщение от "+socket.getInetAddress().getCanonicalHostName()+":\n"+o);
}catch(Exception e){
e.printStackTrace();
System.exit(-1);
}
}
}
But it’s stucked on while loop. Debugger told that there was no -1 value at the end.
What’s wrong here?
Because you’re reading from a Socket, you’ll never reach the end of the stream unless the socket or stream has been closed. So the while loop will block on
input.read()because it won’t return -1 until the client closes the stream/socket.Not really sure what it is you are reading from the socket, but you could try using the BufferedReader’s
readLine()method. You can either know how many lines you need to read ahead of time, or end the reading with a blank line (like HTTP).