gpt4 book ai didi

Java网络对象序列化

转载 作者:行者123 更新时间:2023-12-02 08:03:19 25 4
gpt4 key购买 nike

我试图将一个对象从客户端发送到服务器,其中一个对象状态是一个 vector ,另一个是一个字符串。我可以在服务器端访问该字符串,但服务器端的 vector 内容为零..有人可以帮助我吗..

    // Server
import java.net.*;
import java.util.Vector;
import java.io.*;
public class SimpleServer {

public static void main(String args[]) {
int port = 2002;
try {
System.out.println("Hello");
ServerSocket ss = new ServerSocket(port);
Socket s = ss.accept();
System.out.println("Hello 2");
InputStream is = s.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
testobject to = (testobject)ois.readObject();
System.out.println("Vector size : " + to.vectorX.size() + " and object.id : "
+ to.id);
/* if (to != null) {
for(int i = 0; i < to.vectorX.size(); ++i )
System.out.println("Output 1 : " + to.vectorX.elementAt(i));
} */
is.close();
s.close();
ss.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}


// Client
import java.net.*;
import java.io.* ;
import java.util.Vector;

public class SimpleClient {

protected static Vector<String> vectorX = new Vector<String>();

public SimpleClient(){
vectorX.addElement("hello");
vectorX.add("goodbye");
vectorX.add("finally");
}

public static void main(String args[]) {
try {
new SimpleClient();
Socket s = new Socket("localhost", 2002);
OutputStream os = s.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
testobject to = new testobject(1, "theID", vectorX );
System.out.println(vectorX.size());
oos.writeObject(to);
// oos.writeObject(new String("another object from the client"));
oos.close();
os.close();
s.close();
} catch (Exception e) {
System.out.println(e);
}
}
}


//testobject
import java.net.*;
import java.io. * ;
import java.util.Vector;
class testobject implements Serializable {
int value;
String id;
Vector<String> vectorX;

public testobject(int v, String s, Vector<String> vector) {
this.value = v;
this.id = s;
this.vectorX = new Vector<String>();
}
}

最佳答案

testobject 的构造函数未使用 vector 参数。它是将 vectorX ivar 分配给一个新实例,忽略调用者提供的参数:

public testobject(int v, String s, Vector<String> vector) {
this.value = v;
this.id = s;
this.vectorX = new Vector<String>(); // This is bad
}

您应该使用:

public testobject(int v, String s, Vector<String> vector) {
this.value = v;
this.id = s;
this.vectorX = vector;
}

注意: Java 中的类名全部小写或以小写字母开头的情况并不常见。顺便说一句,我认为你应该将你的类重命名为 TestObject

关于Java网络对象序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8568969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com