【问题标题】:TCP in Android - ObjectOutputStream writeObject failureAndroid 中的 TCP - ObjectOutputStream writeObject 失败
【发布时间】:2013-11-20 16:09:45
【问题描述】:

我正在尝试使用 TCP 套接字通过 WiFi 将对象从我的手机发送到我的 PC(Windows)。当我在两台电脑之间尝试相同的代码时,它可以正常工作。但是当我将客户端代码放到安卓设备上时,它无法使用 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+"'}";
}
}

【问题讨论】:

标签: java android sockets tcp objectoutputstream


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    也许,您需要将此函数添加到 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

    【讨论】:

    • 鉴于他的Message 类的现有定义,完全没有必要。这甚至不如自动发生的事情好,这是一个网络问题,而不是序列化问题。 -1
    猜你喜欢
    • 2014-04-16
    • 1970-01-01
    • 2016-02-23
    • 2018-09-23
    • 2011-05-22
    • 2012-03-26
    • 2023-03-26
    • 2015-01-09
    • 1970-01-01
    相关资源
    最近更新 更多