我在Visual Studio中创建了一个服务器/客户端游戏。这些应用程序通过TCP连接。一切按预期工作后,我在Unity中创建了客户端应用程序。当我在Unity应用程序中玩游戏时,一切正常(客户端与服务器进行通信等)。当我在Windows中导出游戏时,游戏正常。问题是,当我将其导出到Android(apk)时,设备上的游戏无法与服务器通信。
使用调试器,我发现第一个问题(不确定是否还有其他问题)是在我尝试压缩和拆分要发送的程序包时。我将每个软件包拆分为1024个,然后在收件人处重新加入。
pack类:
public class MessageBoxPack
{
private List<MessageBox> msgBoxContainer;
private byte[] msgByte { get; set; }
private MessageBox msgBox;
private int bufferSize;
public List<MessageBox> PrepareMsgBoxList(MessageSlip msg, int _bufferSize)
{
msgBoxContainer = new List<MessageBox>();
bufferSize = _bufferSize;
ConvertMessageToBytes(msg);
return msgBoxContainer;
}
private void ConvertMessageToBytes(MessageSlip msg)
{
BinaryFormatter f = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream gZip = new GZipStream(ms, CompressionMode.Compress))
{
f.Serialize(gZip, msg);
}
byte[] b = ms.ToArray();
int TotalLength = b.Length;
int currentPosition = 0;
int writeLength = bufferSize;
while (currentPosition < TotalLength)
{
msgBox = new MessageBox();
msgBox.CallBackID = msg.CallBackID;
if (currentPosition + bufferSize > TotalLength)
writeLength = TotalLength - currentPosition;
msgBox.MessageBytes = new byte[writeLength];
Array.Copy(b, currentPosition, msgBox.MessageBytes, 0, writeLength);
msgBox.currentPossition = currentPosition;
msgBox.byteLength = TotalLength;
currentPosition += writeLength;
msgBoxContainer.Add(msgBox);
}
}
}
}
和解压缩类:
public class MessageBoxUnpack
{
public MessageSlip UnpackMsgBoxList(List<MessageBox> msgBoxList, int _bufferSize)
{
MessageSlip msg = new MessageSlip();
using (MemoryStream ms = new MemoryStream())
{
foreach (MessageBox msgBox in msgBoxList)
{
//ms.Position = (int)msgBox.currentPossition;
ms.Write(msgBox.MessageBytes, 0, msgBox.MessageBytes.Length);
}
int i = (int)ms.Length;
BinaryFormatter f = new BinaryFormatter();
//ms.Flush();
ms.Position = 0;
//msg = f.Deserialize(ms) as MessageSlip;
using (GZipStream gZip = new GZipStream(ms, CompressionMode.Decompress))
{
msg = f.Deserialize(gZip) as MessageSlip;
}
}
return msg;
}
}
我收到的错误位于
using (GZipStream gZip = new GZipStream(ms, CompressionMode.Compress))
您能告诉我问题出在哪里,如何纠正它,让我知道我使用的打包,拆包和拆分方法是否可以。