I'm pretty new to Java sockets and I'm having problems using the same socket to send and receive data.
The server is on an Android device:
ServerSocket listenSocket = null;
OutputStream dataOutStream = null;
Socket socket = null;
InputStream dataInputStream = null;
// Listen
System.out.println("Start listening");
try {
listenSocket = new ServerSocket(4370);
socket = listenSocket.accept();
System.out.println("Connection accepted");
dataInputStream = socket.getInputStream();
dataOutStream = socket.getOutputStream();
while (dataInputStream.read() != -1);
} catch (IOException e) {
e.printStackTrace();
close(listenSocket, socket);
return;
}
// Answer
System.out.println("Answering...");
byte[] answer = {(byte) 0x82, (byte) 0xf8, 0, 0};
try {
dataOutStream.write(answer);
} catch (IOException e) {
e.printStackTrace();
close(listenSocket, socket);
return;
}
close(listenSocket, socket);
System.out.println("Finished");
The client runs on a Linux machine with Java 6:
Socket socket = new Socket("192.168.1.33", 4370);
OutputStream dataOutputStream = socket.getOutputStream();
InputStream dataInputStream = socket.getInputStream();
byte[] bufferOut = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
dataOutputStream.write(bufferOut);
System.out.println("Sent");
while (dataInputStream.read() != -1);
socket.close();
System.out.println("Finished");
The problem here is that the server gets stuck while (dataInputStream.read() != -1);
line. Looks like the client never closes the sending.
If I do dataOutputStream.close()
in the client part (after writing, of course), then it does work but then the client dies on while (dataInputStream.read() != -1);
saying the socket has been closed.
I want to keep the whole socket open for more data interchange over this same socket until a closing command is sent.
I'm obviously doing something wrong here, any insights? Thanks in advance!