我在从服务器到android应用程序的通信时遇到问题,基本上,通信是这样的:
1. send x and y
2. get the list of coordinates from server
3. send "ok"
4. receive titles string
一切顺利,直到最后一行,我知道它可以正常发送,因为它可以与telnet一起使用,但是我的Android应用程序未收到任何信息。这是用于从客户端发送和接收的代码:
clientSocket = new Socket("10.0.2.2", 1234);
Log.d("LatitudeE6", ""+point.getLatitudeE6());
Log.d("LongitudeE6", ""+point.getLongitudeE6());
os = new PrintStream(clientSocket.getOutputStream());
is = new DataInputStream(clientSocket.getInputStream());
sentenceX = ""+point.getLatitudeE6();
sentenceY = ""+point.getLongitudeE6();
os.println(sentenceX + " "+ sentenceY+'\n');
String thing =is.readLine();
String [] holder = thing.split("\\s+");
System.out.println("thing printed: " +thing);
os.println("ok\n");
String test = is.readLine();
System.out.println("tester: " +test); // this doesn' work
服务器:
try{
in = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
ms.connector();
while(true){
line = in.readLine();
if(line.startsWith("51789181 19426953")==true){
// these are the coordinates, if the client sends them, it will receive the list of other coordinates
os.println(ms.lister().toString().replace('[', ' ').replace(']', ' ').trim().replace(',', ' ') +""+'\n');
os.flush();
}else if ( line.equals("ok")==true) {
os.flush();
os.println(ms.topicDesc().toString().replace('[', ' ').replace(']', ' ').trim().replace(',', ' ') +""+'\n');
}
}
catch(IOException e){
e.printStackTrace();
}
最佳答案
您正在发送两个换行符,一个通过os.println()
,另一个通过"\n"
。这将转换为两行od数据。在客户端,您只是通过readLine()
读取一行。您在服务器和客户端上多次执行此操作。
尝试从客户端和服务器上的发送代码中删除"\n"
。