Komunikacja z serwerem klienta Java
Próbuję pozwolić klientowi (androidowi) komunikować się z serwerem. Wysyłanie danych klienta -> serwer działa poprawnie, ale chcę, aby serwer odpowiedział. Kod po stronie klienta to:
try {
Socket s = new Socket("192.168.0.36", 12390);
s.setSoTimeout(5000);
JSONObject json = new JSONObject();
json.put("emergency", false);
json.put("imei", imei);
json.put("lat", l.getLatitude());
json.put("lon", l.getLongitude());
json.put("acc", l.getAccuracy());
json.put("time", l.getTime());
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
s.getOutputStream()));
out.write(json.toString());
out.newLine();
out.write("###");
out.flush();
Log.d(TAG, "sent");
String inputLine = null;
String result = "";
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
Log.d(TAG, "open input");
while ((inputLine = in.readLine()) != null) {
Log.d(TAG, "while");
if (inputLine.contains("###")) {
break;
}
result = result.concat(inputLine);
}
Log.d(TAG, "closing socket");
s.close();
Strona serwera to:
Socket c = null;
while (true) {
try {
c = s.accept();
} catch (IOException e) {
System.out.println("Accept failed: " + port);
System.exit(-1);
}
try {
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(c.getOutputStream()));
String inputLine = null;
String result = "";
while ((inputLine = in.readLine()) != null) {
if (inputLine.contains("###")) {
System.out.println("received ###");
out.write("Hello phone");
out.newLine();
out.write("###");
out.newLine();
out.flush();
}
result = result.concat(inputLine);
}
System.out.println(result);
out.close();
Serwer poprawnie odczytuje wiadomość od klienta i po otrzymaniu ### powinien odesłać wiadomość, ale klient nie otrzyma jej nigdy. Klient wygasa
while ((inputLine = in.readLine()) != null) {
Log.d(TAG, "while");
if (inputLine.contains("###")) {
break;
}
i nigdy nie wchodzi w pętlę while. Czego mi tu brakuje? Wszelkie pomysły doceniane!