[英]Object lost data while sending through socket
Im trying to send an object back and forth between a client and server and when it leaves the client, all the data is there, ie z = 6.0 but when it reaches the server, all the data is reset, ie z = 0.0 我试图在客户端和服务器之间来回发送对象,当它离开客户端时,所有数据都在那里,即z = 6.0,但是当它到达服务器时,所有数据都被重置,即z = 0.0
I though it might of had something to do with me initializing variable in the object so I don't initialize anything, I also have added a constructor but nothing seems to work. 我虽然可能与我在对象中初始化变量有关,所以我不初始化任何东西,但我也添加了一个构造函数,但似乎没有任何作用。
Object: 宾语:
public class PlayerData implements Serializable{
String name;
int id;
double x,y,z;
double rotation;
PlayerData(String name, double x, double y, double z) {
this.name = name;
this.x = x;
this.y = y;
this.z = z;
id = -1;
}
}
Client Sending: 客户发送:
Thread t = new Thread(){
public void run() {
while(true){
try{
System.out.println("Client writing player z: " + player.z);
streamOut.writeObject(player);
streamOut.flush();
}catch(Exception ioe){
System.out.println("Sending Error: "+ ioe.getMessage());
}
}
}
};
t.start();
Server: 服务器:
boolean done = false;
while(!done) {
//if(streamIn.available() > 0)
try {
Object o = streamIn.readObject();
if(o instanceof PlayerData){
PlayerData recieved = (PlayerData) o;
System.out.println("S: obj recieved z " + recieved.z);
for(int i = 0; i < serv.clientOut.size(); i++) {
serv.clientOut.get(i).writeObject(recieved);
serv.clientOut.get(i).flush();
}
}else
System.out.println("Server: bad object");
}
catch(IOException e) {
done = true;
}
}
And it will say 它会说
Client writing player z: -42.05979919433594
S: obj recieved z 0.0
You're repeated sending the same object via serialization - and ObjectOutputStream
notices that, and instead resolves this to references to the same object. 您通过序列化重复发送同一对象
ObjectOutputStream
注意到这一点,而是将其解析为对同一对象的引用。
If you want to effectively send a separate object on each call, add this to your loop: 如果要在每次调用中有效发送单独的对象,请将其添加到循环中:
streamOut.reset();
That way, every time you write the object, it will write it out as if it's never seen it before (and you'll get a new object on each readObject
call on the other side). 这样,每次编写对象时,它都会将其写出,就像以前从未见过一样(并且在另一侧的每个
readObject
调用中,您都会获得一个新对象)。 Of course, that means the stream will be a lot bigger. 当然,这意味着流会更大。 Personally I'd consider using an alternative serialization technique such as Protocol Buffers, but that's a different matter...
我个人会考虑使用替代的序列化技术,例如协议缓冲区,但这是另一回事...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.