我一直在努力解决这个问题,我真的不知道如何解决这个问题。我正在使用JsonReader
和JsonWriter
与Java服务器进行通信。
写入服务器工作正常,但每当我调用reader.beginArray()
时,我得到EOFException
,所以我不知道如何正确地读取和写入服务器。
错误:
02-19 19:10:07.576: W/System.err(1334): java.io.EOFException: End of input at line 1 column 1
02-19 19:10:07.586: W/System.err(1334): at com.google.gson.stream.JsonReader.nextNonWhitespace(JsonReader.java:943)
02-19 19:10:07.606: W/System.err(1334): at com.google.gson.stream.JsonReader.nextValue(JsonReader.java:771)
02-19 19:10:07.606: W/System.err(1334): at com.google.gson.stream.JsonReader.peek(JsonReader.java:367)
02-19 19:10:07.606: W/System.err(1334): at com.google.gson.stream.JsonReader.expect(JsonReader.java:337)
02-19 19:10:07.617: W/System.err(1334): at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:306)
02-19 19:10:07.617: W/System.err(1334): at com.example.lecture9.MyService.write(MyService.java:40)
02-19 19:10:07.617: W/System.err(1334): at com.example.lecture9.MyService.connect(MyService.java:70)
02-19 19:10:07.626: W/System.err(1334): at com.example.lecture9.MainActivity$1$1.run(MainActivity.java:84)
@Override
public void write(Message msg) throws IOException{
//gson = new Gson();
//writer = new JsonWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream(), "UTF-8")));
//reader = new JsonReader(new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8")));
writer.beginArray();
gson.toJson(msg, msg.getClass(), writer);
writer.flush();
reader.beginArray();
msg = gson.fromJson(reader, Message.class);
System.out.println(msg);
reader.endArray();
writer.endArray();
reader.close();
writer.close();
//try{
//gson.toJson(msg, msg.getClass(), writer);
//writer.flush();
//}
//catch(Exception e){ e.printStackTrace(); }
}
@Override
public boolean connect(String ipAddress, int port) {
Socket s = null;
try{
InetAddress serverAddr = InetAddress.getByName(ipAddress);
s = new Socket(serverAddr, port);
gson = new Gson();
writer = new JsonWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream(), "UTF-8")));
reader = new JsonReader(new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8")));
//writer.beginArray();
Message login = new Message ("CLIENT");
login.getH().setType("LOG");
write(login);
return true;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}