拜托我需要你的帮忙。
我正在使用 TCP 连接在 java 服务器和 android 应用程序客户端之间建立 TCP 连接。假设我将发送一个序列化对象,但是每次在客户端代码都被阻塞在 Obj = (Person)in.readObject; 其中 in 是数据对象输入流,Person 是序列化对象。
但是,如果我发送的是字符串或字符串的整数,则代码正在工作,并且我使用该 Obj = in.readObject; 直接地
所以我需要知道我可以添加什么才能成功反序列化。
或者可能是arraylist只是字符串所以假设我做什么
客户端安卓代码
lst = (ListView) findViewById(R.id.list);
al = new ArrayList<String>();
ad = new ArrayAdapter<String>(this,R.layout.list, al);
try {
socket = new Socket("192.168.0.103", 8888);
in = new ObjectInputStream(socket.getInputStream());
Object obj = null;
while ((obj = in.readObject()) != null) {
if (obj instanceof Person) {
al.add(((Person) obj).toString());
lst.setAdapter(ad);
}}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
finally{
if (in != null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
Java 服务器代码
try {
socket = serverSocket.accept();
oos = new ObjectOutputStream(socket.getOutputStream());
Person person = new Person();
person.setFirstName("James");
person.setLastName("Ryan");
person.setAge(19);
String a = "Ahmed";
oos.writeObject(a);
oos.writeObject(person);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
finally{
if( oos!= null){
try {
oos.flush();
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
序列化对象
public class Person implements Serializable {
private String firstName;
private String lastName;
private int age;
public Person() {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(firstName);
buffer.append("\n");
buffer.append(lastName);
buffer.append("\n");
buffer.append(age);
buffer.append("\n");
return buffer.toString();
}