1

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

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它工作正常!谁能告诉我为什么会这样?

4

2 回答 2

2

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

于 2013-07-15T13:22:46.200 回答
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.javaline 90?您在那里得到一个空指针,它可能与您的网络没有任何关系,而是一个错误/未初始化的引用。

于 2013-07-15T16:24:42.767 回答