【发布时间】:2014-06-05 04:24:01
【问题描述】:
我想知道是否有人在 Google Multiplayer 中使用 RealTime 套接字(而不是消息)。
我有一个代码可以处理从“本机”(IP)套接字派生的流,所以我希望它也可以处理实时套接字流。不幸的是,事实并非如此。
以下代码适用于实时套接字
Sending end:
int s1, s2;
os.write(new byte[] {(byte)s1, (byte)s2};
os.flush(); // May be redundant, according to Google docs
Receiving end:
byte[] buffer = new byte[2];
is.read(buffer);
int r1=buffer[0] & 0xff;
int r2=buffer[1] & 0xff;
但是由于chuck的长度事先是未知的,所以我更喜欢将chunk分成两部分:长度和数据,一个接一个地读取。因此考虑一个不同的代码:
Sending end:
byte s1, s2;
os.write(s1);
os.write(s2);
os.flush();
Receiving end:
int r1=is.read();
int r2=is.read();
在这种情况下,只读取第一个字节,而第二个字节永远不会到来!
由于 Android 文档不推荐刷新,我尝试制作一个包装器,用于在刷新时将多个写入缓存到一个中:
public class OutputStreamWrapper extends OutputStream {
private OutputStream innerOs;
private ByteArrayOutputStream baos;
public OutputStreamWrapper(OutputStream innerOs) {
this.innerOs = innerOs;
baos = new ByteArrayOutputStream();
}
@Override
public void write(int oneByte) throws IOException {
baos.write(oneByte);
}
@Override
public void flush() throws IOException {
if (baos.size() > 0)
innerOs.write(baos.toByteArray());
baos.reset();
}
@Override
public void write(byte[] buffer, int offset, int count)
throws IOException {
baos.write(buffer, offset, count);
}
@Override
public void close() throws IOException {
flush();
innerOs.close();
baos.close();
}
}
问题依旧!
我做错了吗?
如果找不到解决方案,我将不得不编写自定义流作为实时消息的包装器,但避免“即用型”流真的很可惜。
【问题讨论】:
标签: android real-time google-play-services multiplayer