继续获取java.io.StreamCorruptedException:格式错误:ac

时间:2014-08-15 15:55:25

标签: java android sockets serialization

我的Android应用程序在将对象写入流后立即抛出java.io.StreamCorruptedException: Wrong format: ac,即使写入的对象在流的另一端成功读取。令人惊讶的是,从流中读取对象后,异常会在input.readObject()行上抛出。如果我删除了output.writeObject(new String("Android to Server"))行并且没有将任何对象写入流,则input.readObject()会从流中读取所有对象而不会抛出java.io.StreamCorruptedException: Wrong format: ac。通过写入流的android端来触发异常。

起初,我认为问题一定是我写入流中的序列化对象,所以我从两端只向流写了String个对象,异常仍然被抛出。我已经在stackoverflow上检查了几个帖子,但仍然无法找到解决方案。

下面是执行套接字连接,读取和写入的android代码的一部分:

KeyStore keyStore;
try {
    keyStore = KeyStore.getInstance("BKS");
    keyStore.load(getResources().openRawResource(R.raw.keystore), "aQaKP2n5XRyXycT".toCharArray());
    TrustManagerFactory trustManagerFactory = 
                TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    SSLContext sslctx = SSLContext.getInstance("TLS");
    sslctx.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
    SSLSocketFactory factory = sslctx.getSocketFactory();
    SSLSocket socket = (SSLSocket)factory.createSocket("192.168.1.2", 9999);
    ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
    ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
    System.out.println("Connected to server");
    while(true) {
        Object readObject = input.readObject(); // Line 117
        System.out.println(readObject); 
        output.writeObject(new String("Android to Server"));
    }
}

读取和写入流的服务器端。跳过剩下的代码:

while(true) {
  try {
    ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
    ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
    output.writeObject(new String("Hello, World!"));
    Object readObject = input.readObject();
    System.out.println(readObject);
  }
}

下面是打印的堆栈跟踪:

08-14 22:33:09.001: I/System.out(4342): Hello, World!
08-14 22:33:09.011: W/System.err(4342): java.io.StreamCorruptedException: Wrong format: ac
08-14 22:33:09.011: W/System.err(4342):     at java.io.ObjectInputStream.corruptStream(ObjectInputStream.java:676)
08-14 22:33:09.011: W/System.err(4342):     at java.io.ObjectInputStream.readNonPrimitiveContent(ObjectInputStream.java:789)
08-14 22:33:09.011: W/System.err(4342):     at java.io.ObjectInputStream.readObject(ObjectInputStream.java:1981)
08-14 22:33:09.021: W/System.err(4342):     at java.io.ObjectInputStream.readObject(ObjectInputStream.java:1938)
08-14 22:33:09.021: W/System.err(4342):     at com.chatapp.service.TransportService$Client.run(TransportService.java:117)

0 个答案:

没有答案