コード例 #1
0
        void OnReadDataCallback(IAsyncResult ar)
        {
            NetworkStream stream = ar.AsyncState as NetworkStream;

            try
            {
                int numBytes = stream.EndRead(ar);
                receivedBufferDataSize += numBytes;

                while (receivedBufferDataSize >= FrameHeader.StructSize)
                {
                    FrameHeader header = FrameHeader.FromBytes(receivedBuffers[receivedBufferIndex]);
                    if (header.protocolIdentifier != OVRNetwork.FrameHeaderMagicIdentifier)
                    {
                        Debug.LogWarning("[OVRNetworkTcpClient] header mismatch");
                        Disconnect();
                        return;
                    }

                    if (header.payloadLength < 0 || header.payloadLength > OVRNetwork.MaxPayloadLength)
                    {
                        Debug.LogWarningFormat("[OVRNetworkTcpClient] Sanity check failed. PayloadLength %d", header.payloadLength);
                        Disconnect();
                        return;
                    }

                    if (receivedBufferDataSize >= FrameHeader.StructSize + header.payloadLength)
                    {
                        if (payloadReceivedCallback != null)
                        {
                            payloadReceivedCallback(header.payloadType, receivedBuffers[receivedBufferIndex], FrameHeader.StructSize, header.payloadLength);
                        }

                        // swap receive buffer
                        int newBufferIndex    = 1 - receivedBufferIndex;
                        int newBufferDataSize = receivedBufferDataSize - (FrameHeader.StructSize + header.payloadLength);
                        if (newBufferDataSize > 0)
                        {
                            Array.Copy(receivedBuffers[receivedBufferIndex], (FrameHeader.StructSize + header.payloadLength), receivedBuffers[newBufferIndex], 0, newBufferDataSize);
                        }
                        receivedBufferIndex    = newBufferIndex;
                        receivedBufferDataSize = newBufferDataSize;
                    }
                }
                readyReceiveDataEvent.Set();
            }
            catch (SocketException e)
            {
                Debug.LogErrorFormat("[OVRNetworkTcpClient] OnReadDataCallback: socket error: {0}", e.Message);
                Disconnect();
            }
        }