简体   繁体   English

Android实时游戏字节消息传输

[英]Android real time game byte message transfer

Im develop my own game, And i use google play games services to add multiplayer features. 我开发自己的游戏,并使用Google Play游戏服务添加多人游戏功能。

I have a problem with the data messages transfer. 我的数据消息传输有问题。 In default the message object is byte[], And its easy to transfer object like int, char, and cast they back. 默认情况下,消息对象是byte [],它易于传输对象,如int,char并将其强制转换回去。

My problem is to transfer objects i created. 我的问题是转移我创建的对象。

Worked example: 工作示例:

When sending data: 发送数据时:

 int a = 0;
 mMsgBuf[0] = (byte) a;

When reciving: 接收时:

int a = (int) mMsgBuf[0];

Now i want to send my object, But i need to transfer him to a byte (not byte array), and put him in mMsgBuf[X]. 现在我想发送对象,但是我需要将其传输到一个字节(而不是字节数组),然后将其放入mMsgBuf [X]。

How can i do that? 我怎样才能做到这一点?

Edit Its easy to convert object to byte[], but The messages transfer is a byte[]. 编辑它易于将对象转换为byte [], 但是消息传输 byte []。 I'm consulting about how to transfer the message (As we know - byte[]) with my objectbyte[], Maybe merge the two arrays? 我正在咨询如何用我的objectbyte []传输消息(众所周知-byte []),也许合并两个数组?

Make your custom Object serializable if it's not. 使自定义对象不是可序列化的。 Implement Serializable Interface . 实现可序列化接口 Then convert between object and byte array to transfer or receive the data. 然后在对象和字节数组之间转换以传输或接收数据。

Object to byte[]: 对象到字节[]:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(yourObject);
byte[] yourBytes = bos.toByteArray();

byte[] to Object: 字节[]到对象:

ByteArrayIntputSream bis = new ByteArrayInputStream(yourBytes);
ObjectInput in = new ObjectInputStream(bis);
Object o = in.readObject();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM