我试图让(android)客户端与服务器通信。发送数据客户端 - > 服务器工作正常,但我希望服务器响应。客户端代码是:
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();
服务器端是:
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();
服务器正确地从客户端读取消息,并且在接收到### 后应该发回一条消息,但客户端永远不会收到该消息。客户端超时
while ((inputLine = in.readLine()) != null) {
Log.d(TAG, "while");
if (inputLine.contains("###")) {
break;
}
并且永远不会进入while循环。我在这里想念什么?任何想法表示赞赏!