基本上我做了雙方之間的套接字連接。一個Java服務器和一個Android客戶端。我使用Gson庫將對象轉換爲字符串Json,並通過Android客戶端的方法WriteUTF發送它們。但是當我嘗試在Java服務器中得到響應時,我在java.io.DataInputStream.readUnsignedShort(Unknown Source)處得到了一個「java.io.EOFException」。如何,如果我沒有使用這種方法(readUnsignedShort),甚至沒有發送任何Short?這裏是代碼。WriteUTF和ReadUTF,我怎樣才能寫一個字符串,並在另一方得到一個短暫的異常?
來自Android客戶端寫:
try {
DataInputStream in = new DataInputStream (s3.getInputStream());
DataOutputStream out = new DataOutputStream(s3.getOutputStream());
ap = (ArrayList<Produto>) InternalStorage.readObject(getBaseContext(),"pedido");
for(int i=0;i<ap.size()&& ap.size()>0;i++){
Produto p = new Produto("", "", 0f, "", "", 0);
p = ap.get(i);
Gson gson = new Gson();
String json = gson.toJson(p);
out.writeUTF(json);
out.flush();
}
而且從Java服務器閱讀:
try {
// Get input from the client
DataInputStream in = new DataInputStream (server.getInputStream());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
while((line = in.readUTF()) != null) {
boolean error = false;
String json = line;
Gson gson = new Gson();
Produto p2 = gson.fromJson(json, Produto.class);
c = dbDelegate.getCommandByNumber(p2.getMesa());
p = dbDelegate.getProductByName(p2.getNome());
if(c!=null && p!=null){
error = false;
inCommand.setCommand(c);
inCommand.setDateAndTime(new Timestamp(System.currentTimeMillis()));
inCommand.setProduct(p);
inCommand.setLogin(FishingBoardFrameCashRegister.getInstance().getLogin());
inCommand.setQuantity(p2.getQuantidade());
inCommand.setPrice(String.valueOf((p2.getValor()*p2.getQuantidade())));
inCommand.setObs(p2.getObs());
inCommand.setProductName(p.getName());
inCommand.setType(Product.ALL);
inCommand.setSession(0);
inCommand.setCommandSession(c.getSession());
if(dbDelegate.insertProductInCommand(inCommand) == DbDelegate.CASH_CLOSED){
error = true;
}
FishingBoardFrameCashRegister.getInstance().updateTable();
}else{
error = true;
}
日誌可以幫助過:
trueIOException on socket listen: java.io.EOFException
java.io.EOFException
at java.io.DataInputStream.readUnsignedShort(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
at com.keymax.server.doComms3.run(Server3.java:71)
Server3.java:71是這條線在服務器代碼中:while((line = in.readUTF())!= null){
明白了。優秀的解決方案!我會嘗試一下,比我在這裏發佈我的結果。謝謝 ! –