[英]How to pass objects correctly between java and android using Sockets TCP?
I am trying to send an object using TCP/IP using an Android application an a Java application. 我正在尝试使用Android应用程序和Java应用程序使用TCP / IP发送对象。 But I'm having the problem that the information coming is null.
但是我遇到的问题是,输入的信息为空。
The object belongs to a class called Mensaje, and in both projects has the same package name and have the same serialVersionUID: 该对象属于一个名为Mensaje的类,并且在两个项目中都具有相同的程序包名称和相同的serialVersionUID:
package CLASSESS;
import java.io.Serializable;
public class Mensaje implements Serializable{
// private static final long serialVersionUID = 5950169519310163575L;
private static final long serialVersionUID = 9178463713495656548L;
public static int TYPE;
public static int ID;
public static String DATA;
}
The Android application class implements Serializable and handles the conexion into a Threat Android应用程序类实现Serializable并处理对威胁的威胁
public class SocketClient implements Serializable{
private Runnable send_ObjectMessage = new Runnable(){
public void run(){
try {
obj_Mensaje = new Mensaje();
obj_Mensaje.TYPE = 1;
obj_Mensaje.ID = 2;
obj_Mensaje.DATA= "hOKA MUNDO";
salida_mensaje = new ObjectOutputStream(socket_cliente.getOutputStream());
salida_mensaje.writeObject(obj_Mensaje);
salida_mensaje.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
The Server has the same Mensaje class and implements Serializable with the same serialVersionUID; 服务器具有相同的Mensaje类,并使用相同的serialVersionUID实现Serializable;
The server reads the object on a Threat. 服务器在Threat上读取对象。
@Override
public void run() {
try {
obj_message_read = new Mensaje();
ois_readMessage = new ObjectInputStream(clientSocket.getInputStream());
while(clientSocket.isConnected()){
Object aux = ois_readMessage.readObject();
if(aux instanceof Mensaje){
obj_message_read = (Mensaje)aux;
setDATA(obj_message_read.DATA);
setTYPE(obj_message_read.TYPE);
setID(obj_message_read.ID);
System.out.println("Data" + obj_message_read.DATA);
}
}
}catch (IOException ioe){
ioe.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
The problem is that the information coming in the Mensaje is null. 问题在于进入Mensaje的信息为空。 So when i print
System.out.println("Data" + obj_message_read.DATA);
所以当我打印
System.out.println("Data" + obj_message_read.DATA);
the Server prints 服务器打印
Data Null
数据为空
I think the problem is that the fields you are trying to send are declared as static
, which are transient for serialization. 我认为问题在于您尝试发送的字段被声明为
static
,对于序列化来说是临时的。
Change it removing that keyword: 对其进行更改以删除该关键字:
public class Mensaje implements Serializable{
// private static final long serialVersionUID = 5950169519310163575L;
private static final long serialVersionUID = 9178463713495656548L;
public int TYPE;
public int ID;
public String DATA;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.