通过ObjectInputStream接收对象

时间:2013-07-15 12:55:10

标签: java serialization io nullpointerexception objectinputstream

我正在使用Java在Android和Windows上编写服务器 - 客户端应用程序。我想将用户的信息(用户名和密码)发送到服务器进行验证。客户端发送包含信息的对象,但服务器没有收到它! 这是Object类:

package Model;

import java.io.Serializable;

public class StringObject implements Serializable {

private static final long serialVersionUID = 1L;
private String Username=null;
private String Password=null;

public void setPassword(String Password){
    this.Password=Password;
}
public void setUsername(String Username){
    this.Username=Username;
}
public String getPassword(){
    return Password;
}
public String getUsername(){
    return Username;
}
}

客户端代码:

private void Login(){
    try {
ObjectOutputStream OutObj=new  ObjectOutputStream(newBufferedOutputStream(connection.getOutputStream()));
                OutObj.writeObject(UserPass);
                OutObj.flush();
            } catch (IOException e) {
        Log.d("Application: ",e.toString());}

(我在这行之前设置了Object变量)

和服务器代码:

  ObjectInputStream inObj = new ObjectInputStream(new         BufferedInputStream(connection.getInputStream()));
        UserPass=(StringObject) inObj.readObject();
        System.out.println("UserName: " + UserPass.getUsername());
        System.out.println("Password: " + UserPass.getPassword());

客户端程序(android)因错误而崩溃:线程退出时未捕获异常。 (套接字和I / O代码行在一个单独的线程中)

07-15 12:43:59.626: W/dalvikvm(1306): threadid=13: thread exiting with uncaught exception (group=0x40a71930)
07-15 12:43:59.626: E/AndroidRuntime(1306): FATAL EXCEPTION: Thread-89
07-15 12:43:59.626: E/AndroidRuntime(1306): java.lang.NullPointerException
07-15 12:43:59.626: E/AndroidRuntime(1306):     at com.shayan.filesharing.ConnectionThread.Login(ConnectionThread.java:90)
07-15 12:43:59.626: E/AndroidRuntime(1306):     at com.shayan.filesharing.ConnectionThread.ProcessMessage(ConnectionThread.java:70)
07-15 12:43:59.626: E/AndroidRuntime(1306):     at com.shayan.filesharing.ConnectionThread.run(ConnectionThread.java:47)

但是当我用ObjectOutputStream / ObjectInputStream替换BufferedWriter / bufferedReader时,它运行正常!谁能告诉我为什么会这样?

2 个答案:

答案 0 :(得分:2)

不要为每个事务创建新的对象流。在插座的两端使用相同的流。对象流读取和写入标头,因此每个套接字创建多个实例只是与另一端不同步。

答案 1 :(得分:0)

引用:

   07-15 12:43:59.626: E/AndroidRuntime(1306): java.lang.NullPointerException
   07-15 12:43:59.626: E/AndroidRuntime(1306):     at com.shayan.filesharing.ConnectionThread.Login(ConnectionThread.java:90)
   07-15 12:43:59.626: E/AndroidRuntime(1306):     at com.shayan.filesharing.ConnectionThread.ProcessMessage(ConnectionThread.java:70)
   07-15 12:43:59.626: E/AndroidRuntime(1306):     at com.shayan.filesharing.ConnectionThread.run(ConnectionThread.java:47)

您可以在ConnectionThread.java上显示罚款line 90吗?你在那里得到一个nullpointer,它可能与你的网络没有任何关系,但是一个坏的/未初始化的引用。