Ejemplo n.º 1
0
        /// <summary>
        /// 当接收到数据之后的回调函数
        /// </summary>
        /// <param name="ar"></param>
        private void ReadCallback(IAsyncResult ar)
        {
            TcpTransmitBox stateOne = (TcpTransmitBox)ar.AsyncState;
            Socket         handler  = stateOne.WorkSocket;

            try
            {
                int bytesRead = handler.EndReceive(ar);
                if (bytesRead > 0)
                {
                    //取缓存区的数据
                    byte[] haveDate = ReceiveData.DateOneManage(stateOne, bytesRead);//接收完成之后对数组进行重置
                    handler.BeginReceive(stateOne.Buffer, 0, stateOne.Buffer.Length, 0, new AsyncCallback(ReadCallback), stateOne);
                    UnpackStickyData(stateOne, haveDate);
                }
                else
                {
                    handler.BeginReceive(stateOne.Buffer, 0, stateOne.Buffer.Length, 0, new AsyncCallback(ReadCallback), stateOne);
                }
            }
            catch (Exception Ex)
            {
                int i = Ex.Message.IndexOf("远程主机强迫关闭了一个现有的连接");
                if (stateOne != null && i != -1)
                {
                    socketRemove(stateOne, Ex.Message);
                }
            }
        }
Ejemplo n.º 2
0
        static async Task Main(string[] args)
        {
            var channel = GrpcChannel.ForAddress("https://localhost:5001");

            var client = new GetData.GetDataClient(channel);

            while (true)
            {
                Console.Write("Please enter the topic: ");
                string topic = Console.ReadLine();
                Console.Write("Please enter the message: ");
                string message = Console.ReadLine();
                var    input   = new ReceiveData {
                    Topic = topic, Message = message
                };
                var reply = await client.GetDataInfoAsync(input);

                //Console.WriteLine($"{reply.Message}");
            }

            /*var input = new HelloRequest { topic = "N***a" };
             * var reply = await client.SayHelloAsync(input);
             * Console.WriteLine(reply.Message);*/
            Console.ReadLine();
        }
Ejemplo n.º 3
0
            public void SetReceiveData(ReceiveData _data)
            {
                short tlen = SReadShort(mBuffer, mPos);

                _data.SetBuffer(mBuffer, mPos);
                mPos = tlen + SocketDataBase.mPackageTopLen;
            }
Ejemplo n.º 4
0
        /// <summary>
        /// 当接收到数据之后的回调函数
        /// </summary>
        /// <param name="ar"></param>
        private void ReadCallback(IAsyncResult ar)
        {
            if (stateOne == null)
            {
                return;
            }
            Socket handler = stateOne.WorkSocket;

            try
            {
                int bytesRead = handler.EndReceive(ar);
                if (bytesRead > 0)
                {
                    //MessageBox.Show(stateOne.Buffer[0].ToString());
                    byte[] haveDate = ReceiveData.DateOneManage(stateOne, bytesRead);//接收完成之后对数组进行重置

                    handler.BeginReceive(stateOne.Buffer, 0, stateOne.Buffer.Length, 0, new AsyncCallback(ReadCallback), stateOne);
                    UnpackStickyData(stateOne, haveDate);
                }
                else
                {
                    handler.BeginReceive(stateOne.Buffer, 0, stateOne.Buffer.Length, 0, new AsyncCallback(ReadCallback), stateOne);
                }
            }
            catch (Exception Ex)
            {
                lostClient(Ex.Message);//当突然断开的时候
            }
        }
Ejemplo n.º 5
0
        public JsonResult SendIO(string port1, string port2, string deviceid)
        {
            ReceiveData temp = new ReceiveData();
            string      data;
            var         username = HttpContext.Session.GetString("UserName");
            var         oridata  = deviceid + "000000003004" + port1 + port2 + "0001";
            var         t        = Regex.Split(oridata, "(?<=\\G.{2})");
            int         j        = 0;

            byte[] b = new byte[t.Length - 1];
            try
            {
                foreach (var item in t)
                {
                    b[j] = Convert.ToByte(item, 16);
                    j++;
                    if (j == t.Length - 1)
                    {
                        break;
                    }
                }
                var check = CRC.ToCRC16(b, false);
                data      = "fe" + deviceid + "000000003004" + port1 + port2 + "0001" + check + "fe";
                temp.Data = data;
                temp.Time = DateTime.Now;
                temp.Id   = _context.ReceiveData.Max(x => x.Id) + 1;
                _context.Add(temp);
                _context.SaveChanges();
            }
            catch (Exception)
            {
            }
            return(null);
        }
Ejemplo n.º 6
0
            public ReceiveData GetReceiveData()
            {
                ReceiveData ret = new ReceiveData();

                SetReceiveData(ret);
                return(ret);
            }
Ejemplo n.º 7
0
        private void AsyncReceiveCallBack(IAsyncResult IA)
        {
            Socket socket = IA.AsyncState as Socket;

            if (socket != null && socket.Connected)
            {
                try
                {
                    int    datalength = (IA.AsyncState as Socket).EndReceive(IA);
                    string msg        = "";
                    if (datalength == 0)//1.断开连接
                    {
                        Disconnect();
                        OnServerClose?.Invoke(this, "服务器断开连接");
                    }
                    else
                    {
                        msg = Encoding.Default.GetString(_buffer, 0, datalength);
                        if (_heartBeatEnable && msg == "HEARTBEAT")//2.心跳数据解析
                        {
                            _alive = true;
                        }
                        else
                        {
                            ReceiveData?.Invoke(this, msg);//3.数据接收
                        }
                    }
                }
                catch
                { }
            }
        }
Ejemplo n.º 8
0
        private async void OnUpdate()
        {
            while (!Server.Instance.IsShutdown())
            {
                ClockConstantController.Start("raknetUpdate");

                if (this.receiveDataQueue.Count > 0)
                {
                    ReceiveData data = null;
                    this.receiveDataQueue.TryDequeue(out data);
                    this.HandlePacket(data.Point, data.Data);
                }

                string[] bl = this.blockUsers.Keys.ToArray();
                for (int i = 0; i < bl.Length; ++i)
                {
                    this.blockUsers[bl[i]] -= 1;
                    if (this.blockUsers[bl[i]] <= 0)
                    {
                        int r = 0;
                        this.blockUsers.TryRemove(bl[i], out r);
                    }
                }

                RakNetSession[] sl = this.sessions.Values.ToArray();
                for (int i = 0; i < sl.Length; ++i)
                {
                    sl[i].Update();
                }

                await ClockConstantController.Stop("raknetUpdate");
            }
        }
Ejemplo n.º 9
0
        private void Connect_Click(object sender, RoutedEventArgs e)
        {
            // Connet UR Secondary Port
            urSec = IURSecondaryConnection.Create(IPAddress.Text);
            var resp = urSec.Receive();

            // Connet UR RTDE port
            rtde = IURRTDEConnection.Create(IPAddress.Text);
            var np = new NegotiateProtocolVersion(rtde);

            Logging.Text += $"NegotiateProtocolVersion Accepted: { np.Accepted }";

            ControllerVersion cv = new ControllerVersion(rtde);

            Logging.Text += $"Controller Version: major { cv.Major }" +
                            $" minor { cv.Minor } bugfix { cv.Bugfix } build { cv.Build }";

            string      vars     = "timestamp,actual_TCP_pose,actual_q,runtime_state";
            SetupOutput setupOut = new SetupOutput(rtde, 125, vars);

            Logging.Text += $"Setup Output: output recipe id { setupOut.OutputRecipeId }" +
                            $" variable types { setupOut.VariableTypes }";

            var ss = new StartSending(rtde);

            rd = new ReceiveData(rtde, setupOut.VariableTypes);

            var task = new Task(() => ReceiveRTDE());

            task.Start();
        }
Ejemplo n.º 10
0
        public void Recv_Complete()
        {
            var sendRequest = new SendRequest
            {
                AgentState = AgentLocation.MN,
                Country    = Country.Usa,
                State      = State.Ny,
                SendCurr   = Currency.Usd,
                AmtRange   = AmountRange.NoIdsNoThirdParty,
                FeeType    = ItemChoiceType1.amountExcludingFee
            };

            sendRequest.PopulateAgentData(sendRequest.AgentState);
            var sendData       = new SendData(sendRequest);
            var receiveRequest = new ReceiveRequest
            {
                AgentState     = AgentLocation.NY,
                ThirdPartyType = TestThirdPartyType.None
            };

            receiveRequest.PopulateAgentData(receiveRequest.AgentState);

            var receiveData = new ReceiveData(receiveRequest);

            sendData = SendOperations.SendCompleteForNewCustomer(sendData);
            receiveData.Set(sendData);
            receiveData = ReceiveOperations.ReceiveComplete(receiveData);
            var transLookupResponse = TranLookupOperations.TransactionLookupForStatus(receiveRequest.AgentId, receiveRequest.AgentPos, receiveData.CompleteSessionResponse.Payload.ReferenceNumber);

            // ASSERT ALL THE THINGS
            Assert.IsFalse(sendData.Errors.Any(), $" {Environment.NewLine}Errors: {Environment.NewLine}{sendData.Errors?.Log()}");
            Assert.IsFalse(receiveData.Errors.Any(), $" {Environment.NewLine}Errors: {Environment.NewLine}{sendData.Errors?.Log()}");
            Assert.IsTrue(transLookupResponse.TransactionLookupResp.Payload.TransactionStatus == TransactionStatusType.RECVD);
        }
Ejemplo n.º 11
0
 // This method is invoked when an asynchronous receive operation completes.
 // If the remote host closed the connection, then the socket is closed.
 // If data was received then the data is echoed back to the client.
 //
 private void ProcessReceive(SocketAsyncEventArgs e)
 {
     try
     {
         // check if the remote host closed the connection
         if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
         {
             UserToken token = (UserToken)e.UserToken;
             //将数据包交给后台处理,这里你也可以新开个线程来处理.加快速度.
             ReceiveData?.Invoke(token, e.Buffer.Skip(e.Offset).Take(e.BytesTransferred).ToArray());
             //继续接收. 为什么要这么写,请看Socket.ReceiveAsync方法的说明
             if (!token.Socket.ReceiveAsync(e))
             {
                 ProcessReceive(e);
             }
         }
         else
         {
             CloseClientSocket(e);
         }
     }
     catch (Exception ex)
     {
         Error?.Invoke(ex);
     }
 }
Ejemplo n.º 12
0
        //*********************************************************************************************
        // ReceivedForget
        // Recebe o pedido para que o servidor envie os dados perdidos do jogados
        //*********************************************************************************************
        public static void ReceivedForget(int index, string data)
        {
            string[] packet = data.Replace("<67>", "").Split(';');
            if (packet.Length != 2)
            {
                return;
            }
            if (!ReceiveData.IsNumeric(packet[0]))
            {
                return;
            }
            if (Convert.ToInt32(packet[0]) > 1)
            {
                return;
            }
            if (Convert.ToInt32(packet[0]) < 0)
            {
                return;
            }
            if (packet[1].Length > 100)
            {
                return;
            }
            if (packet[1].Length < 5)
            {
                return;
            }

            Mail.Send_Account(index, 1, packet[1]);
        }
Ejemplo n.º 13
0
 /// <summary>
 /// 移除监听器
 /// </summary>
 /// <param name="listener"></param>
 public void RemoveIistListeners(ReceiveData listener)
 {
     if (listenerManage.Contains(listener))
     {
         listenerManage.Remove(listener);
     }
 }
Ejemplo n.º 14
0
 /// <summary>
 /// 添加监听器
 /// </summary>
 /// <param name="listener"></param>
 public void AddListeners(ReceiveData listener)
 {
     if (!listenerManage.Contains(listener))
     {
         listenerManage.Add(listener);
     }
 }
Ejemplo n.º 15
0
        public void Recv_ValidationUntilReadyForCommit()
        {
            var sendRequest = new SendRequest
            {
                AgentState = AgentLocation.MN,
                Country    = Country.Usa,
                State      = State.Ny,
                SendCurr   = Currency.Usd,
                AmtRange   = AmountRange.NoIdsNoThirdParty,
                FeeType    = ItemChoiceType1.amountExcludingFee
            };

            sendRequest.PopulateAgentData(sendRequest.AgentState);
            var sendData       = new SendData(sendRequest);
            var receiveRequest = new ReceiveRequest
            {
                AgentState     = AgentLocation.NY,
                ThirdPartyType = TestThirdPartyType.None
            };

            receiveRequest.PopulateAgentData(receiveRequest.AgentState);

            var receiveData = new ReceiveData(receiveRequest);

            SendOperations.SendCompleteForNewCustomer(sendData);
            receiveData.Set(sendData);
            ReceiveOperations.ValidateUntilReadyForCommitForReceive(receiveData);

            var receiveValidationResponse = receiveData.ReceiveValidationResponses?.FirstOrDefault();

            // ASSERT ALL THE THINGS
            Assert.IsFalse(sendData.Errors.Any(), $" {Environment.NewLine}Errors: {Environment.NewLine}{sendData.Errors?.Log()}");
            Assert.IsTrue(receiveValidationResponse != null && receiveValidationResponse.Payload.ReadyForCommit);
        }
Ejemplo n.º 16
0
        // METHODS
        public void Run()
        {
            while (true)
            {
                ReceiveData data = consumer.Receive(int.Parse(configuration["RabbitMq:MillisecondsReceiveTimeout"]));

                if (data != null)
                {
                    // show data
                    Console.WriteLine(data.Message);

                    // try to serialize
                    string errorMessage = string.Empty;
                    try
                    {
                        SerializeData(data.Message);
                    }
                    catch (Exception e)
                    {
                        errorMessage = e.Message;
                    }
                    // send to server serialization status
                    SendSerializationResultData(errorMessage);

                    // processed message
                    consumer.SetAcknowledge(data.DeliveryTag, processed: true);
                }
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Initializes the ModuleClient and sets up the callback to receive
        /// messages containing temperature information
        /// </summary>
        static async Task Init()
        {
            AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only);

            ITransportSettings[] settings = { amqpSetting };

            // Open a connection to the Edge runtime
            ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);

            await ioTHubModuleClient.OpenAsync();

            IoTHubModuleClient = ioTHubModuleClient as ModuleClient;
            Console.WriteLine("IoT Hub module client initialized.");

            // Register callback to be called when a message is received by the module
            //await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", PipeMessage, ioTHubModuleClient);

            _temperature = new Garage();
            _temperature.ReadTemperatureAsync();
            _temperature.LedMatrixAsync();

            //Receive IoTHub commands
            _receiveData = new ReceiveData();
            _receiveData.ReceiveCommandsAsync();
        }
Ejemplo n.º 18
0
        public static void Insert(ReceiveData info, string ACID)
        {
            int deviceType = 0;

            if (info != null)
            {
                var State = false;
                switch (info.DeviceType)
                {
                case "0100":
                    State      = GasData(info, ACID);
                    deviceType = 8;
                    break;

                case "0200":
                    State      = SmokeData(info, ACID);
                    deviceType = 7;
                    break;

                default:
                    break;
                }
                if (State)
                {
                    JudgementAlarm(info, deviceType, ACID);
                }
            }
        }
Ejemplo n.º 19
0
        private FileInput GetInputData(ReceiveData receiveData)
        {
            FileInput input = receiveData.GetObject <FileInput>();

            getDataInputConsumer.SetAcknowledge(receiveData.DeliveryTag, true);
            return(input);
        }
Ejemplo n.º 20
0
        private void TimerCallback(object state)
        {
            void TryRead()
            {
                var bytes = new byte[BUFFER_SIZE];

                if (device.BytesToRead < 0)
                {
                    throw new Exception("adapter disconnected");
                }

                while (device.BytesToRead >= BUFFER_SIZE)
                {
                    if (device.ReadByte() == ReceivedData.START_MARKER)
                    {
                        bytes[0] = ReceivedData.START_MARKER;
                        device.Read(bytes, 1, BUFFER_SIZE - 1);

                        var data = ReceivedData.Parse(bytes);
                        ReceiveData?.Invoke(this, data);

                        if (data.Command == MTRFXXCommand.MicroclimateData && data.DataFormat == (byte)MTRFXXDataFormat.MicroclimateData)
                        {
                            var microclimateData = new MicroclimateData(bytes);
                            ReceiveMicroclimateData?.Invoke(this, microclimateData);
                        }
                    }
                }
            }

            ThreadSafeExec(true, TryRead, Close);
        }
Ejemplo n.º 21
0
        public IHttpActionResult PostRecive(ReceiveData receiveData)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));          // 400 Bad Request
            }
            #region 紀錄Log
            var Receive_Procedure_Respons = SQLMethod.Receive_Procedure(receiveData);
            switch (Receive_Procedure_Respons)
            {
            case 0:
            {
                return(Ok(SQLMethod.Receive_Procedure_ErrorStr));;
            }

            case 1:
            {
                return(Ok(SQLMethod.Receive_Procedure_ErrorStr));
            }

            default:
            {
                return(BadRequest(SQLMethod.Receive_Procedure_ErrorStr));
            }
            }
            #endregion
        }
Ejemplo n.º 22
0
        public async Task SendAsync(IRequest request)
        {
            if (!_tcpClient.Connected)
            {
                await _tcpClient.ConnectAsync(IPAddress.Parse(_userSettings.GetString("ServerIP")), _userSettings.GetInt32("ServerPort"));
            }

            if (request is IConnectionRequiredRequest connectionRequiredRequest)
            {
                connectionRequiredRequest.ConnectionIdentifier0 = _connectionIdentification.Current[0];
                connectionRequiredRequest.ConnectionIdentifier1 = _connectionIdentification.Current[1];
                connectionRequiredRequest.ConnectionIdentifier2 = _connectionIdentification.Current[2];
                connectionRequiredRequest.ConnectionIdentifier3 = _connectionIdentification.Current[3];
            }

            request.Counter = ++_counter;
            await _tcpClient.WriteAsync(_requestBuilder.Build(request));

            var dataBytes = await _tcpClient.ReadAsync();

            var response = _responseParser.Parse(dataBytes);

            if (response.IsNotConnectedResponse())
            {
                await SendAsync(new ConnectDataRequest());
                await SendAsync(request);
            }

            ReceiveData?.Invoke(response);
        }
Ejemplo n.º 23
0
 private void Receiver_ClientDataReceived(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
 {
     if (e.Error == null)
     {
         ReceiveData data = e.UserState as ReceiveData;
         if (data != null)
         {
             MessageData msg = data.clientData as MessageData;
             if ((msg != null) && (msg.id > 0))
             {
                 Console.WriteLine("<<< Client: {0} -- Received Msg from Server >>>", msg.handle);
                 if (!Dispatcher.CheckAccess())
                 {
                     Dispatcher.Invoke(BankClientControl.dataAction, msg);
                 }
                 else
                 {
                     BankClientControl.dataAction.Invoke(msg);
                 }
                 currentNumEmptyRcv = 0;
             }
             else
             {
                 ++currentNumEmptyRcv;
                 if (currentNumEmptyRcv == MaxEmptyRcv)
                 {
                     Close();
                 }
             }
         }
     }
 }
Ejemplo n.º 24
0
        /// <summary>
        /// Initializes the ModuleClient and sets up the callback to receive
        /// messages containing temperature information
        /// </summary>
        static async Task Init()
        {
            MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);

            ITransportSettings[] settings = { mqttSetting };

            // Open a connection to the Edge runtime
            IoTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);

            await IoTHubModuleClient.OpenAsync();

            Console.WriteLine("IoT Hub module client initialized.");

            // Register callback to be called when a message is received by the module
            //await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", PipeMessage, ioTHubModuleClient);

            //initialize Raspberry
            _raspberryPins = new Pins();
            _raspberryPins.ConnectGpio();
            _raspberryPins.LoopGpioPins();

            _paradox1738 = new Paradox1738();
            _paradox1738.ParadoxSecurity();
            _paradox1738.IRSensorsReading();

            //Receive Netatmo data
            _receiveNetatmoData = new ReceiveNetatmoData();
            _receiveNetatmoData.ReceiveData();

            //read from ome temperature sensors
            _homeTemperature = new HomeTemperature();
            _homeTemperature.ReadTemperature();

            //Starting schedulers
            _co2Scheduler = new Co2();
            _co2Scheduler.CheckCo2Async();

            _saunaHeating = new SaunaHeating();
            _saunaHeating.CheckHeatingTime();

            _heatingScheduler = new Heating();
            _heatingScheduler.ReduceHeatingSchedulerAsync();

            //Receive IoTHub commands
            _receiveData = new ReceiveData();
            _receiveData.ReceiveCommandsAsync();

            //query WiFiProbes
            _wiFiProbes = new WiFiProbes();
            _wiFiProbes.QueryWiFiProbes();

            //shelly's
            TelemetryDataClass.isOutsideLightsOn = await Shelly.GetShellyState(Shelly.OutsideLight);

            SomeoneAtHome.CheckLightStatuses();

            //Send data to IoTHub
            _sendData = new SendTelemetryData();
            _sendData.SendTelemetryEventsAsync();
        }
        private bool ReceiveMessage(TcpClient client)
        {
            try
            {
                if (client.Available > 0)
                {
                    var stream = client.GetStream();

                    var readLength = stream.Read(m_Buffer, 0, m_Buffer.Length);

                    if (readLength > 0)
                    {
                        ReceiveData?.Invoke(
                            this,
                            new SocketReceiveEventArgs
                        {
                            Client = client,
                            Data   = m_Buffer,
                            Length = readLength
                        });
                    }
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Ejemplo n.º 26
0
    void GameStart(ReceiveData rev)
    {
        var revData = rev.MsgObject as CustomProtocol.GameStart;

        playerId       = revData.playId;
        localFrameTick = revData.serverTick;
        localFrameTick++;
        Debug.Log("the server playerid :" + playerId + "udpPort:" + revData.udpPort + "playerCount:" + revData.playerList.Count);
        foreach (var x in revData.playerList)
        {
            Debug.Log("当前场景里得玩家:" + x.playId);
            var entity = this.entityMgr.CreatePlayerEntity(x);
            if (x.playId == playerId)
            {
                //currenty player
                curPlayer = entity;
            }
            var f = new Frame();
            f.playerEntity = entity;
            f.PlayerId     = x.playId;
            allPlayerServerFrame[x.playId] = f;
        }
        NetWorkManager.Instance.CloseTcp();
        NetWorkManager.Instance.InitUdp(revData.udpPort);
        serverGameStart = true;
        timeInterval    = 0;


        FollowCamera.target = curPlayer.UnityTransform;
        //test
        //var o = new CustomProtocol.PlayerConnectRsp();
        //o.playId = playerId + 1;
        //NetWorkManager.Instance.SendUDP(o);
    }
Ejemplo n.º 27
0
    void ReceiveData(byte[] data)
    {
        ByteArray       byteArray   = new ByteArray(data, (short)data.Length);
        ReceiveDataType type        = (ReceiveDataType)byteArray.readChar();
        ReceiveData     receiveData = new ReceiveData();

        switch (type)
        {
        case ReceiveDataType.Response:
            checkConfirm(byteArray.readInt(), byteArray.readChar());
            break;

        case ReceiveDataType.Transform:
            receiveData.cmd       = type;
            receiveData.transform = ReceiveTransformData.readFromBytes(byteArray.readBytes());
            callback(receiveData);
            break;

        case ReceiveDataType.Action:
            receiveData.cmd = type;
            SendResponse(byteArray.readInt());
            receiveData.action = ReceiveActionData.readFromBytes(byteArray.readBytes());
            callback(receiveData);
            break;

        case ReceiveDataType.State:
            receiveData.cmd = type;
            SendResponse(byteArray.readInt());
            receiveData.state = ReceiveStateData.readFromBytes(byteArray.readBytes());
            callback(receiveData);
            break;
        }
    }
Ejemplo n.º 28
0
        /// <summary>
        /// Callback for data received
        /// </summary>
        /// <param name="result"></param>
        private void DataReceived(IAsyncResult result)
        {
            ReceiveData data = (ReceiveData)result.AsyncState;
            int         n    = data.networkStream.EndRead(result);

            //FIN packet creates data received event with 0 bytes
            if (n > 0)
            {
                byte[] received = new byte[n];
                char[] cstr     = new char[n + 1];
                for (int i = 0; i < n; i++)
                {
                    received[i] = data.readBuffer[i];
                    cstr[i]     = (char)data.readBuffer[i];
                }
                cstr[n] = '\0';
                //Debug.Log("[KSPEthernetIO]: " + n + " bytes received:\n" + new String(cstr));

                //Async wait for next data
                WaitForData(data.networkStream);

                //Notify listeners
                NotifyDataReceived(received);
            }
            else
            {
                Debug.LogWarning("[KSPEthernetIO]: Connection closed. Restarting TCP Server!");
                Restart();
            }
        }
Ejemplo n.º 29
0
 public ReceiveData ReceiveComplete(ReceiveData receiveData)
 {
     try
     {
         receiveData.ReceiveRequest.PopulateAgentData(receiveData.ReceiveRequest.AgentState);
         // Get the all fields grouping and types for generation
         receiveData.Set(_gafOperations.GetInfoKeysWithGroupTypes(receiveData.ReceiveRequest.AgentId, receiveData.ReceiveRequest.AgentPos, receiveData.GafInfoKeysWithGroups, GetAllFieldsTransactionType.Receive));
         // Transaction Lookup Request
         CreateTransactionLookupRequest(receiveData);
         // Transaction Lookup Response
         TransactionLookup(receiveData);
         // Initial Validate Receive
         _validationOperations.RecvValidate(receiveData, receiveData.ReceiveRequest.ThirdPartyType);
         if (DataErrorHandler.CheckForNestedErrors(receiveData).Any())
         {
             throw new AgentConnectException();
         }
         _validationOperations.RecvValidateUntilReadyForCommit(receiveData);
         if (DataErrorHandler.CheckForNestedErrors(receiveData).Any())
         {
             throw new AgentConnectException();
         }
         CompleteSession(receiveData);
     }
     catch (AgentConnectException acExp)
     {
         receiveData.Set(new BusinessError
         {
             ErrorCategory = "AC Exception",
             ErrorCode     = acExp.ErrorCode.ToString(),
             Message       = acExp.Message
         });
     }
     return(receiveData);
 }
Ejemplo n.º 30
0
        /// <summary>
        /// 接收到信息的回调函数
        /// </summary>
        /// <param name="iar"></param>
        private void EndReceiveFromCallback(IAsyncResult iar)
        {
            int byteRead = 0;

            try
            {
                //完成接收
                byteRead = state.WorkSocket.EndReceiveFrom(iar, ref state.RemoteEP);
            }
            catch { }
            if (byteRead > 0)
            {
                state.IpEndPoint = (IPEndPoint)state.RemoteEP;
                byte[] haveDate = ReceiveData.DateOneManage(state, byteRead);//接收完成之后对数组进行重置
                BeginReceiveFrom();
                int havePort = UdpPortSetGet.GetPort(ref haveDate);
                if (havePort != 0)
                {
                    state.IpEndPoint.Port = havePort;
                }
                DataModel statecode = ReceiveData.DataValidation(haveDate);
                codeManage(state, statecode);
            }
            else
            {
                BeginReceiveFrom();
            }
        }
Ejemplo n.º 31
0
        private void Echo_Req(ReceiveData data)
        {
            _counter.Add(1);

            Packet resPacket = new Packet(Protocol.Echo_Res);
            Send(data.Sender as EndPoint, resPacket);
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Receive a complete IMap reply including literals and untagged
        /// responses.
        /// </summary>
        /// <param name="data">A structure containing the received data.</param>
        /// <returns><c>true</c> on success.</returns>
        public bool Receive(out ReceiveData data)
        {
            data = new ReceiveData();
            data.State = Receive(ref data, out data.Literals);
            bool exists = false;                    // flag to invoke Messages() callback

            // fetch all info data and all literals ...
            if(data.State == ReceiveState.Info)
            {   List<string>    infos = new List<string>();
                List<byte[]>    multi = null;
                do {
                    infos.Add(data.Status);
                    infos.Add(data.Message);
                    byte[][] literals;
                    data.State = Receive(ref data, out literals);
                    if(literals != null)
                    {   if(data.Literals == null)
                            data.Literals = literals;
                        else
                        {   if(multi == null)
                            {   multi = new List<byte[]>();
                                foreach(byte[] elt in data.Literals) multi.Add(elt);
                            }
                            foreach(byte[] elt in literals) multi.Add(elt);
                        }
                    }
                } while(data.State == ReceiveState.Info);

                // process the received info data array ...
                int icnt = infos.Count / 2;
                data.Infos = new ZIMapProtocol.ReceiveInfo[icnt];
                for(int irun=0; irun < icnt; irun++)
                {   data.Infos[irun].Status  = infos[irun*2];
                    string message           = infos[irun*2+1];
                    data.Infos[irun].Message = message;

                    // check for "* nn EXISTS" messages ...
                    if(exists_cnt != uint.MaxValue && message == "EXISTS")
                    {   uint ecnt = 0;
                        if(uint.TryParse(infos[irun*2], out ecnt))
                        {   exists_cnt = ecnt;  exists = true;
                        }
                    }
                }
                if(multi != null)
                    data.Literals = multi.ToArray();
            }

            // EXISTS count callback
            if(exists)
                MonitorInvoke(ZIMapConnection.Monitor.Messages, exists_cnt.ToString());

            // check for errors
            switch(data.State)
            {   case ReceiveState.Info:
                case ReceiveState.Error:
                case ReceiveState.Failure:
                case ReceiveState.Ready:   return true;
                default:                   return false;
            }
        }
        /// <summary>
        /// Create a dynamic virtual channel 
        /// </summary>
        /// <param name="priority">Priority</param>
        /// <param name="channelName">Channel name</param>
        /// <param name="transportType">Transport type</param>
        /// <param name="receiveCallBack">Callback method called when received data</param>
        /// <returns>DVC created</returns>
        public DynamicVirtualChannel CreateChannel(TimeSpan timeout, ushort priority, string channelName, DynamicVC_TransportType transportType, ReceiveData receiveCallBack = null, uint? channelId = null)
        {
            if (!transportDic.ContainsKey(transportType))
            {
                throw new InvalidOperationException("Not create DVC transport:" + transportType);
            }

            if (channelId == null)
                channelId = DynamicVirtualChannel.NewChannelId();
            DynamicVirtualChannel channel = new DynamicVirtualChannel((UInt32)channelId, channelName, priority, transportDic[transportType]);

            if (receiveCallBack != null)
            {
                // Add event method here can make sure processing the first DVC data packet
                channel.Received += receiveCallBack;
            }

            channelDicbyId.Add((UInt32)channelId, channel);

            this.SendDVCCreateRequestPDU(priority, (UInt32)channelId, channelName, transportType);
            CreateRespDvcPdu createResp = this.ExpectDVCCreateResponsePDU(timeout, (UInt32)channelId, transportType);
            if (createResp == null)
            {
                throw new System.IO.IOException("Creation of channel: " + channelName + " failed, cannot receive a Create Response PDU");
            }
            if (createResp.CreationStatus < 0)
            {
                //Create failed
                throw new System.IO.IOException("Creation of DVC failed with error code: " + createResp.CreationStatus + ", channel name is " + channelName);
            }

            return channel;
        }
        /// <summary>
        /// Establish a DVC after received a Create Request PDU
        /// </summary>
        /// <param name="createReq"></param>
        /// <param name="transportType"></param>
        /// <param name="receiveCallBack"></param>
        private void EstablishChannel(CreateReqDvcPdu createReq, DynamicVC_TransportType transportType, ReceiveData receiveCallBack = null)
        {
            if (channelDicbyId.ContainsKey(createReq.ChannelId))
            {
                throw new InvalidOperationException("Cannot establish the DVC, since a channel with same channelId have been established. Channel ID is " + createReq.ChannelId);
            }

            DynamicVirtualChannel channel = new DynamicVirtualChannel(createReq.ChannelId, createReq.ChannelName, (ushort)createReq.HeaderBits.Sp, transportDic[transportType]);
            if (receiveCallBack != null)
            {
                // Add event method here can make sure processing the first DVC data packet
                channel.Received += receiveCallBack;
            }
            else
            {
                if (callBackMethodsDic != null && callBackMethodsDic.ContainsKey(createReq.ChannelName))
                {
                    channel.Received += callBackMethodsDic[createReq.ChannelName];
                }
            }

            channelDicbyId.Add(createReq.ChannelId, channel);

            this.SendDVCCreateResponsePDU(createReq.ChannelId, 0, transportType);
        }
        /// <summary>
        /// Expect to create a SVC
        /// </summary>
        /// <param name="timeout">Timeout</param>
        /// <param name="channelName">Channel Name</param>
        /// <param name="transportType">Transport Type</param>
        /// <returns></returns>
        public DynamicVirtualChannel ExpectChannel(TimeSpan timeout, string channelName, DynamicVC_TransportType transportType, ReceiveData receiveCallBack = null)
        {
            if (autoCreateChannel)
            {
                throw new InvalidOperationException("Cannot establish a DVC manually if autoCreateChannel is true!");
            }

            if (!transportDic.ContainsKey(transportType))
            {
                throw new InvalidOperationException("Not create DVC transport:" + transportType);
            }

            CreateReqDvcPdu createReq = this.ExpectDVCCreateRequestPDU(timeout, channelName, transportType);
            if (createReq == null)
            {
                throw new System.IO.IOException("Creation of channel: " + channelName + " failed, cannot receive a Create Request PDU");
            }

            DynamicVirtualChannel channel = new DynamicVirtualChannel(createReq.ChannelId, channelName, (ushort)createReq.HeaderBits.Sp, transportDic[transportType]);
            if (receiveCallBack != null)
            {
                // Add event method here can make sure processing the first DVC data packet
                channel.Received += receiveCallBack;
            }
            else
            {
                if (callBackMethodsDic != null && callBackMethodsDic.ContainsKey(channelName))
                {
                    channel.Received += callBackMethodsDic[channelName];
                }
            }

            channelDicbyId.Add(createReq.ChannelId, channel);

            this.SendDVCCreateResponsePDU(createReq.ChannelId, 0, transportType);

            return channel;
        }
Ejemplo n.º 36
0
 /// <summary>
 /// Receive a single line of an IMap reply (no literals)
 /// </summary>
 /// <param name="tag"><c>0</c> for an untagged response or the
 /// tag number of the command.</param>
 /// <param name="status">The status text like OK, NO or BAD</param>
 /// <param name="message">The response text.</param>
 /// <returns>A value indicating success or failure.</returns>
 /// <remarks>
 /// A convenience overload that ignores literals.
 /// </remarks>
 public ReceiveState Receive(out uint tag, out string status, out string message)
 {
     ReceiveData data = new ReceiveData();
     ReceiveState stat = Receive(ref data, out data.Literals);
     tag = data.Tag;
     status = data.Status;
     message = data.Message;
     if(data.Literals != null)
         MonitorError("Receive: literal data ignored");
     return stat;
 }
Ejemplo n.º 37
0
        // internal helper to process a single response line
        private ReceiveState Receive(ref ReceiveData data, out byte[][] literals)
        {
            literals = null;
            if(transport == null)                        // connection is closed
            {   RaiseError(ZIMapException.Error.DisposedObject);
                return ReceiveState.Exception;
            }

            object info;
            try
            {   string tags;
                if(transport.Receive(out tags, out data.Status,
                                     out data.Message, out literals))
                {
                    // --- check the tag ---

                    if(tags == "*" || tags == "0")
                    {   if(data.Status == "BYE")
                        {   bye_received = true;
                            MonitorInfo( "Receive: 'BYE' will close transport");
                        }
                        return ReceiveState.Info;
                    }
                    if(tags == "+")
                        return ReceiveState.Continue;
                    if(!uint.TryParse(tags, System.Globalization.NumberStyles.AllowHexSpecifier,
                                      null, out data.Tag))
                    {   RaiseError(ZIMapException.Error.UnexpectedTag, "Tag: " + tags);
                        return ReceiveState.Exception;
                    }

                    // --- check the status ---

                    data.State = ReceiveState.Error;
                    if(data.Status == "OK")
                    {   if(bye_received)                    // server sent untagged BYE
                        {   transport.Close();
                            ZIMapConnection.Callback.Closed(connection);
                        }
                        data.State = ReceiveState.Ready;
                    }
                    else if(data.Status == "NO")
                        data.State = ReceiveState.Failure;
                    else if(data.Status != "BAD")
                    {   RaiseError(ZIMapException.Error.UnexpectedData, "Status: " + data.Status);
                        return ReceiveState.Exception;
                    }

                    ZIMapConnection.Callback.Result(connection, data);
                    return data.State;
                }
                else if(transport.IsClosed)
                {   ZIMapConnection.Callback.Closed(connection);
                    return ReceiveState.Closed;
                }
                info = "transport timeout";
            }
            catch(Exception inner)
            {   info = inner;
            }
            RaiseError(ZIMapException.Error.ReceiveFailed, info);
            return ReceiveState.Exception;
        }