0

我无法通过我的网络发送大约 1.5 mb 的图像文件。我已将 NetworkManager 配置为使用 QoSType ReliableFragmented,但它显然不起作用。我究竟做错了什么?附上 NetworkManager 组件的代码和屏幕截图。

我收到的错误是:

NetworkWriter WriteBytes: buffer is too large (1699064) bytes. The maximum buffer size is 64K bytes.
UnityEngine.Networking.NetworkWriter:WriteBytesFull(Byte[])
TextureMessage:Serialize(NetworkWriter)
UnityEngine.Networking.NetworkServer:SendToAll(Int16, MessageBase)
Server:SendTexture(Texture2D, String) (at Assets/Scripts/Server.cs:41)
Server:SendOnButtonPress() (at Assets/Scripts/Server.cs:28)
UnityEngine.EventSystems.EventSystem:Update()

启动网络和序列化数据的代码

纹理消息.cs

using UnityEngine.Networking;

public class TextureMessage : MessageBase
{
    public byte[] textureBytes;
    public string message; //Optional
}

MyMsgType.cs

using UnityEngine.Networking;

public class MyMsgType
{
    public static short texture = MsgType.Highest + 1;
}

服务器.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class Server : MonoBehaviour {

    public Texture2D textureToSend;
    string messageToSend = "Test Message";

    // Use this for initialization
    void Start ()
    {
        NetworkManager.singleton.StartHost();
        Debug.Log("Server Started.");
    }

    public void SendOnButtonPress()
    {
        SendTexture(textureToSend, messageToSend);
    }

    //Call to send the Texture and a simple string message
    public void SendTexture(Texture2D texture, string message)
    {
        TextureMessage msg = new TextureMessage();

        //Convert Texture2D to byte array

        msg.textureBytes = texture.GetRawTextureData();
        msg.message = message;

        NetworkServer.SendToAll(MyMsgType.texture, msg);
    }
}

网络管理器组件

4

1 回答 1

0

它是如何在内部工作的。

NetworkServer.SendToAll():

static public bool SendToAll(short msgType, MessageBase msg)
{
    if (LogFilter.logDev) { Debug.Log("Server.SendToAll msgType:" + msgType); }
    bool result = true;

    // this list holds all connections (local and remote)
    for (int i = 0; i < connections.Count; i++)
    {
        NetworkConnection conn = connections[i];
        if (conn != null)
            result &= conn.Send(msgType, msg);
    }

    return result;
}

NetworkConnection 公共构造函数:

public NetworkConnection()
{
    m_Writer = new NetworkWriter();
}

网络连接.发送():

public virtual bool Send(short msgType, MessageBase msg)
{
    return SendByChannel(msgType, msg, Channels.DefaultReliable);
}

NetworkConnection.SendByChannel():

public virtual bool SendByChannel(short msgType, MessageBase msg, int channelId)
{
    m_Writer.StartMessage(msgType);
    msg.Serialize(m_Writer);
    m_Writer.FinishMessage();
    return SendWriter(m_Writer, channelId);
}

如您所见,它使用 NetworkWriter 来序列化您的消息。NetworkWriter 有大小为 64Kb 的缓冲区。您不能序列化大于 64K 的对象。所以你至少有两个解决方案:

  1. 将您的纹理碎片化为小于 64K 的块的数组/列表,并逐步连贯地发送它。

  2. 重写所有网络代码。

于 2017-10-18T19:57:47.170 回答