Android中的TCP - ObjectOutputStream writeObject失败

时间:2013-11-08 15:26:30

标签: java android sockets tcp objectoutputstream

我正在尝试通过WiFi使用TCP套接字将手机中的对象发送到我的PC(Windows)。当我在两台PC之间尝试相同的代码时,它没有任何错误。但是当我将客户端代码放到android设备上时,它无法使用writeObject方法发送日期。但writeUTF命令有效。它给出“软件导致的连接中止:recv failed”错误。以下是代码。请帮忙..

服务器(在PC中):

public class Test {

public static void main(String arg[]) {
    ServerSocket serverSocket = null;
    Socket socket = null;
    ObjectInputStream in = null;
    ObjectOutputStream out = null;


    try {
        serverSocket = new ServerSocket(8888);
        System.out.println("Listening :8888");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    while (true) {
        try {
            socket = serverSocket.accept();
            in = new ObjectInputStream(socket.getInputStream());
            out = new ObjectOutputStream(socket.getOutputStream());
            out.flush();

            System.out.println("ip: " + socket.getInetAddress());
            Message msg = (Message) in.readObject();  //Message captured from chat client.
            System.out.println(msg.type + " message received from " + msg.sender + " Containing " + msg.content);
            out.writeObject(new Message("Ack", "Server", "Message Received", "Client"));
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } 



        finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}
}

客户端(在Android设备中):

public class MainActivity extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button bb=(Button)findViewById(R.id.button1);

    bb.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            new Send().execute();

        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
 private class Send extends AsyncTask<Void, Void, Void> {
        Socket socket = null;
        ObjectOutputStream out = null;
        ObjectInputStream in = null;

     protected Void doInBackground(Void... arg0) {

            try {
                socket = new Socket("192.168.43.92", 8888); //use the IP address of the server
                out = new ObjectOutputStream(socket.getOutputStream());
                out.flush();

                out.writeObject(new Message("Chat", "Server", "Hello World", "Server")); //This method is used to write something to the server.
                out.flush();

                Message msg = (Message) in.readObject();
                System.out.println(msg.type + " message received from " + msg.sender + " Containing " + msg.content);


            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 

            finally {

                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }            





         return null;            
     }

     protected void onProgressUpdate(Integer... progress) {
         //setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         //showDialog("Downloaded " + result + " bytes");
     }
 }

}

消息(双方都有):

public class Message implements Serializable{

private static final long serialVersionUID = 1L;
public String type, sender, content, recipient;

public Message(String type, String sender, String content, String recipient){
    this.type = type; this.sender = sender; this.content = content; this.recipient = recipient;
}

@Override
public String toString(){
    return "{type='"+type+"', sender='"+sender+"', content='"+content+"', recipient='"+recipient+"'}";
}
}

2 个答案:

答案 0 :(得分:0)

客户端和服务器之间的网络是否通过WiFi正确设置?下载其中一个ping&amp; telnet测试应用程序并使用它来测试您的网络连接。

Telnet是一个有用的TCP调试应用程序。如果您有一台服务器正在侦听11.22.33.44端口1234,您应该可以telnet 11.22.33.44 1234

答案 1 :(得分:-1)

也许,您需要将此功能添加到Message类:

private void writeObject(java.io.ObjectOutputStream stream)
         throws IOException {
     stream.writeObject(type);
     stream.writeObject(sender);
     stream.writeObject(content);
     stream.writeObject(recipient);
 }


 private void readObject(java.io.ObjectInputStream stream)
         throws IOException, ClassNotFoundException {
     type = (String) stream.readObject();
     sender = (String) stream.readObject();
     content = (String) stream.readObject();
     recipient = (String) stream.readObject();

 }

http://developer.android.com/reference/java/io/Serializable.html