示例#1
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            // Retrieve the state object and the client socket from the asynchronous state object.
            StateObject state = (StateObject)ar.AsyncState;

            try
            {
                // Read data from the remote device.
                int bytesRead = state.WorkSocket.EndReceive(ar);
                if (bytesRead == 0)
                {
                    // Socket Shutdown is complete, so lets disconnect
                    _socket.BeginDisconnect(true,
                                            new AsyncCallback(DisconnectCallback), _socket);
                    _disconnectDone.WaitOne();
                    return;
                }

                if (EOL != null)
                {
                    string rcvd = Encoding.ASCII.GetString(state.DataRcvd, 0, bytesRead);
                    if (state.TextRcvd == null)
                    {
                        state.TextRcvd = new StringBuilder();//...this must be the first receive
                    }
                    state.TextRcvd.Append(rcvd);

                    if (rcvd.EndsWith(EOL))
                    {
                        // Signal that all bytes have been received.
                        _receiveDone.Set();
                    }

                    // Bubble the event
                    if (OnDataIn.GetInvocationList().Length > 0)
                    {
                        OnDataIn(this, state.DataRcvd);
                    }
                }
                else
                {
                    // Get the actual data received, and put it into a dynamically sized buffer
                    byte[] buffer = new byte[bytesRead];
                    Buffer.BlockCopy(state.DataRcvd, 0, buffer, 0, bytesRead);

                    // Clear the buffer
                    state.DataRcvd = new byte[state.BufferSize];

                    // Bubble the event
                    OnDataIn(this, buffer);
                }

                // Wait for more data
                Receive(_bufferSize);
            }
            catch (Exception exc)
            {
                if (OnError.GetInvocationList().Length > 0)
                {
                    OnError(this, exc);
                }
            }
        }
        private void HandleReceivedData(byte[] inData)
        {
            if (debugLevel > 3)
            {
                string dString = Encoding.ASCII.GetString(inData);
                Debug.Log(dString.Length + "  " + (byte)inData[0] + "  " + dString);
            }

            byte magicByte = inData[0];

            if (magicByte == 100)
            {
                string json = Encoding.ASCII.GetString(inData, 1, inData.Length - 1);
                try {
                    AnswerObject obj = JsonUtility.FromJson <AnswerObject>(json);
                    if (obj.type == "answer")
                    {
                        if (debugLevel > 1)
                        {
                            Debug.Log("MM Answer: " + obj.address + ":" + obj.port);
                        }
                        _remoteAddress = obj.address;
                        _remotePort    = obj.port;
                        Punch();
                        Punch();
                    }
                    if (obj.type == "punch")    // received punch packet from other client -> connection works
                    {
                        lastReceivedHB = currentTime;
                        connected      = true;
                    }
                    return; // return if package was a json package
                } catch (Exception e) { Debug.Log(e.ToString()); }
            }
            else     //if (magicByte == 0x14) {
            {
                lastReceivedHB = currentTime;
                OIMSG msg = new OIMSG();

                using (MemoryStream str = new MemoryStream(inData)) {
                    using (BinaryReader reader = new BinaryReader(str)) {
                        msg.msgFamily = reader.ReadByte();
                        msg.msgType   = reader.ReadByte();
                        UInt16 unused2 = reader.ReadUInt16();
                        msg.sequenceID  = reader.ReadUInt32();
                        msg.partsAm     = reader.ReadUInt32();
                        msg.currentPart = reader.ReadUInt32();
                        msg.timestamp   = reader.ReadUInt64();
                    }
                }

                msg.data = new byte[inData.Length - headerLen];
                Array.Copy(inData, headerLen, msg.data, 0, inData.Length - headerLen);

                //if (debugLevel > 1) Debug.Log("family: "+msg.msgFamily+" type: " +msg.msgType+" packageSequenceID:  " + msg.sequenceID + ", partsAm: " + msg.partsAm + ", currentPart: " + msg.currentPart + ", size: " + inData.Length);
                if (debugLevel > 1)
                {
                    Debug.Log("family: " + msg.msgFamily + " type: " + msg.msgType + ", partsAm: " + msg.partsAm + ", currentPart: " + msg.currentPart);
                }
                if (msg.partsAm == 1)
                {
                    lock (_receiveQueueLock) {
                        _receiveQueue.Enqueue(msg);
                    }
                    if (OnDataIn != null)
                    {
                        OnDataIn.Invoke(msg);
                    }
                }
                else if (msg.partsAm > 1)
                {
                    if (!_dataParts.ContainsKey(msg.sequenceID))
                    {
                        byte[][] parts = new byte[msg.partsAm][];
                        parts[msg.currentPart - 1] = msg.data;
                        _dataParts.Add(msg.sequenceID, parts);
                    }
                    else
                    {
                        byte[][] parts = _dataParts[msg.sequenceID];
                        parts[msg.currentPart - 1] = msg.data;

                        bool dataComplete   = true;
                        int  concatDataSize = 0;
                        for (int i = 0; i < msg.partsAm; i++)
                        {
                            if (parts[i] == null)
                            {
                                dataComplete = false;
                                break;
                            }
                            concatDataSize += parts[i].Length;
                        }
                        if (dataComplete)
                        {
                            _dataParts.Remove(msg.sequenceID);
                            byte[] concatData = new byte[concatDataSize];
                            int    idx        = 0;
                            for (int i = 0; i < msg.partsAm; i++)
                            {
                                Array.Copy(parts[i], 0, concatData, idx, parts[i].Length);
                                idx += parts[i].Length;
                            }

                            msg.data = concatData;
                            lock (_receiveQueueLock)
                                _receiveQueue.Enqueue(msg);
                            if (OnDataIn != null)
                            {
                                OnDataIn.Invoke(msg);
                            }
                        }
                    }
                }
            }

            /*
             * else {
             *  lastReceivedHB = currentTime;
             *  if (OnDataIn != null) OnDataIn.Invoke(inData);
             *  lock (_receiveQueueLock)
             *      _receiveQueue.Enqueue(inData);
             * }
             */
        }