我試圖讓(android)客戶端與服務器進行通信。發送數據客戶端 - >服務器工作正常,但我希望服務器響應。客戶端代碼:Java服務器 - 客戶端套接字通信
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循環。我在這裏錯過了什麼?任何想法讚賞!
這實際上是它!我沒有注意到它,因爲服務器記錄了「System.out.println(」received ###「);」,但那個人解決了它。謝謝一堆! – FWeigl 2012-07-26 09:46:10