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!
edit : Olaf showed a built-in way to realize the request-response scenario in the question.
Closing a stream obtained from a socket also closes the socket (see also).On the other hand it is impossible for the InputStream obtained from a socket to see if all the data was sent as long as the stream/socket is open(there could be more bits on its way!). A 2-way communication can not work this way, unless using Olafs example. That allows to wait for the server response.
What you can do is define an end-signal yourself (e.g. the string “END”) and either side listens until that end signal is read, then writes. But that comes with all sorts of other problems you will encounter for sure (what if the sent text contains the end signal? what if the partner dies before sending end? timeouts?…). see also
I would try and look at SOAP or RESTful services that are well supported in Java (but I don’t know how well on Android). Generally there are many libraries that tackle these problems for you and relieve you from the low level networking. It almost always pays off to use an existing solution.