I want to pop an event in a job and store a pointer to the internal sub array of that data so that I can later parse the data in other jobs.
I cannot use the DataStreamReader with ReadBytes in this case because I am inside a job and cannot allocate temp memory (with ReadBytes) and return that as it’s not allowed.
Passing in a pre-allocated block of memory to the job increases code complexity and I really don’t want to do that.
I’ve made a tiny modification to NetworkDriver to work around this. It’s probably unsafe.
My ParsePacketsJob
See how PopEventForConnection now outputs a NativeArray instead of DataStreamReader
while ((cmd = Driver.PopEventForConnection(Connections[index], out NativeArray<byte> bytes)) != NetworkEvent.Type.Empty)
{
if (cmd == NetworkEvent.Type.Data)
{
var reader = new DataStreamReader(bytes);
PacketType type = Packets.ReadPacketType(ref reader);
reader.SeekSet(0);
ReceivedMessages.Add((int) type, new PacketArrayWrapper()
{
Pointer = bytes.GetUnsafeReadOnlyPtr(),
Length = bytes.Length,
InternalId = Connections[index].InternalId
});
}
else if (cmd == NetworkEvent.Type.Disconnect)
{
Debug.Log("Client disconnected from server");
Connections[index] = default(NetworkConnection);
}
}
Modification of NetworkDriver.cs
Added
public NetworkEvent.Type PopEventForConnection(NetworkConnection connectionId, out NativeArray<byte> bytes)
{
return PopEventForConnection(connectionId, out bytes, out var _);
}
public NetworkEvent.Type PopEventForConnection(NetworkConnection connectionId, out NativeArray<byte> bytes, out NetworkPipeline pipeline)
{
pipeline = default;
bytes = default;
if (connectionId.m_NetworkId < 0 || connectionId.m_NetworkId >= m_ConnectionList.Length ||
m_ConnectionList[connectionId.m_NetworkId].Version != connectionId.m_NetworkVersion)
return (int)NetworkEvent.Type.Empty;
var type = m_EventQueue.PopEventForConnection(connectionId.m_NetworkId, out var offset, out var size, out var pipelineId);
pipeline = new NetworkPipeline { Id = pipelineId };
if (type == NetworkEvent.Type.Disconnect && offset < 0)
bytes = m_DisconnectReasons.GetSubArray(math.abs(offset), 1);
else if (size > 0)
bytes = ((NativeArray<byte>)m_DataStream).GetSubArray(offset, size);
return type;
}