Example #1
0
 public void OnEventRaised()
 {
     if (Response == null)
     {
         Debug.LogWarning("No Response", this);
     }
     _dataVariable.Data = null;
     Response?.Invoke(_dataVariable);
 }
Example #2
0
    private static void ListenForData(object client)
    {
        TcpClient     tcpClient    = (TcpClient)client;
        NetworkStream clientStream = tcpClient.GetStream();

        byte[] message = new byte[4096];
        int    bytesRead;

        while (true)
        {
            bytesRead = 0;
            try
            {
                bytesRead = clientStream.Read(message, 0, 4096);
            }
            catch
            {
                break;
            }
            if (bytesRead == 0)
            {
                DisconnectionEvent?.Invoke(null, new SocketConnectionMsg(tcpClient, tcpClient.Client.RemoteEndPoint.ToString()));
                break;
            }
            ASCIIEncoding encoder = new ASCIIEncoding();
            string        msg     = encoder.GetString(message, 0, bytesRead);
            DataEvent?.Invoke(null, new SocketDataMsg(tcpClient.Client.RemoteEndPoint.ToString(), msg));
        }
        tcpClient.Close();
    }
Example #3
0
    // Update is called once per frame
    void Update()
    {
        recBuffer = new byte[1024];
        NetworkEventType recData = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error);

        switch (recData)
        {
        case NetworkEventType.Nothing:
            break;

        case NetworkEventType.ConnectEvent:
            ConnectionEvent?.Invoke(null,
                                    new UnetConnectionMsg(recHostId, connectionId, channelId, "", 0));
            break;

        case NetworkEventType.DataEvent:
            DataEvent?.Invoke(null, new UnetDataMsg(hostId, connectionId, channelId, System.Text.Encoding.UTF8.GetString(recBuffer)));
            break;

        case NetworkEventType.DisconnectEvent:
            DisconnectionEvent?.Invoke(null,
                                       new UnetConnectionMsg(recHostId, connectionId, channelId, "", 0));
            break;
        }
    }
Example #4
0
    void Update()
    {
        if (UnetServerStarted)
        {
            byte[]           recBuffer = new byte[1024];
            int              recHostId, connectionId, channelId, dataSize;
            byte             error;
            NetworkEventType recData = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, 1024, out dataSize, out error);
            switch (recData)
            {
            case NetworkEventType.Nothing:
                break;

            case NetworkEventType.ConnectEvent:
                NetworkID id;
                NodeID    dstNode;
                string    clientIp;
                int       port;
                NetworkTransport.GetConnectionInfo(hostId, connectionId, out clientIp, out port, out id,
                                                   out dstNode, out error);
                ConnectionEvent?.Invoke(null,
                                        new UnetConnectionMsg(hostId, connectionId, channelId, clientIp.Split(':')[3], port));
                break;

            case NetworkEventType.DataEvent:
                string msg = System.Text.Encoding.Default.GetString(recBuffer);
                DataEvent?.Invoke(null, new UnetDataMsg(hostId, connectionId, channelId, msg));
                break;

            case NetworkEventType.DisconnectEvent:
                DisconnectionEvent?.Invoke(null, new UnetConnectionMsg(hostId, connectionId, channelId, "", 0));
                break;
            }
        }
    }
Example #5
0
        void HandleData(int connectionId, int channelId, int receivedSize, NetworkError error)
        {
            var client = FindConnection(connectionId);

            if (client == null)
            {
                return;
            }

            client.LastError = error;

#if NETWORK_DEBUGGER_ENABLED
            var logMessage = new System.Text.StringBuilder("ServerPeer");
            logMessage.Append(" Incoming");
            logMessage.Append(" ConnectionId:").Append(connectionId);
            logMessage.Append(" ChannelId:").Append(channelId);
            logMessage.Append(" Size:").Append(receivedSize);

            UnityEngine.Debug.Log(logMessage);
#endif

#if NETWORK_PROFILER_ENABLED && UNITY_EDITOR
            var profilerName = new System.Text.StringBuilder("ServerPeer");
            profilerName.Append(channelId);
            Profiler.NetworkProfiler.RecordChannelIncoming(profilerName.ToString(), (ushort)receivedSize);
#endif
            if (DataEvent != null)
            {
                DataEvent.Invoke(client, channelId, m_RecievedBuffer, receivedSize);
            }
        }
Example #6
0
    public void OnDataEvent(int socketID, int connectionId, byte[] buffer, NetworkError error)
    {
        DataEvent?.Invoke();

        var JsonText = Encoding.Unicode.GetString(buffer);

        NetworkMessage message = JsonConvert.DeserializeObject <NetworkMessage>(JsonText);

        switch (message.MessageType)
        {
        case DataEvents.ConnectionInfoRequest:     // Get connection info and save in connections pool
            //OnConnectionInfoEvent(hostId, connectionId, message, buffer, error);
            break;

        case DataEvents.PlayRequest:     // if connection response is ok, continue. Else, disconnect from node.
            PlayRequest?.Invoke();
            break;

        case DataEvents.PecasDoJogo:     // if connection response is ok, continue. Else, disconnect from node.
            try
            {
                DominoPecas dominoPecas = JsonConvert.DeserializeObject <DominoPecas>(message.Message.ToString());
                GlobalConfigInfo.blockchain.CreateTransaction(GlobalConfigInfo.CurrentAdversary.connectedNode.nickName, GlobalConfigInfo.ThisNode.nickName, dominoPecas);
                PecasDoJogo?.Invoke(dominoPecas);
            }
            catch (Exception e)
            {
                string exc = e.ToString();
            }
            break;

        case DataEvents.PlayerMove:     // call event to deal with this event and every gameplay script who sould know about network info should do your action
            try
            {
                Peca peca = JsonConvert.DeserializeObject <Peca>(message.Message.ToString());
                GlobalConfigInfo.blockchain.CreateTransaction(GlobalConfigInfo.CurrentAdversary.connectedNode.nickName, GlobalConfigInfo.ThisNode.nickName, peca);
                PecaEvent?.Invoke(peca);
            }
            catch (Exception e)
            {
                string exc = e.ToString();
            }

            //PlayerMove?.Invoke();

            break;

        case DataEvents.EndGame:     // call event to deal with this event and every gameplay script who sould know about network info should do your action
            EndGame?.Invoke();
            break;
        }

        print("|Data event: " +
              "/n|HostId: " + socketID +
              "/n|ConnectionId : " + connectionId +
              "/n|Error: " + error.ToString());
    }
Example #7
0
    protected override void OnMessage(MessageEventArgs e)
    {
        var name = Context.QueryString["name"];

        if (e.IsText)
        {
            messageReceived?.Invoke(this, e.Data);
        }
        else if (e.IsBinary)
        {
            dataReceived?.Invoke(this, e.RawData);
        }
    }
Example #8
0
        void HandleDataEvent(int channelId, int receivedSize)
        {
#if NETWORK_DEBUGGER_ENABLED
            UnityEngine.Debug.Log($"ClientPeer Incoming : ChannelId:{channelId} Size:{receivedSize}");
#endif

#if NETWORK_PROFILER_ENABLED && UNITY_EDITOR
            var profilerName = new StringBuilder(PROFILER_CATEGORY_PREFIX);
            profilerName.Append(channelId);
            NetworkProfiler.RecordChannelIncoming(profilerName.ToString(), (ushort)receivedSize);
#endif

            DataEvent?.Invoke(channelId, m_RecievedBuffer, receivedSize);
        }
Example #9
0
        static public void OutputHandle(long threadid, string opdata)
        {
            HookParam hp = ThreadHandleDict[threadid];

            hp.Text = opdata;

            DataEvent?.Invoke(typeof(Textractor), hp);
            if (!string.IsNullOrWhiteSpace(GameConfig.HookCode) &&
                GameConfig.HookCode == hp.Hookcode &&
                (GameConfig.ThreadContext & 0xFFFF) == (hp.Ctx & 0xFFFF) &&
                GameConfig.SubThreadContext == hp.Ctx2)
            {
                log.Info(hp.Text);
                SelectedDataEvent?.Invoke(typeof(Textractor), hp);
            }
        }
Example #10
0
        static public void OutputHandle(long threadid, string opdata)
        {
            HookParam hp = ThreadHandleDict[threadid];

            hp.Text = opdata;

            DataEvent?.Invoke(typeof(Textractor), hp);

            if (gameInfo.HookCode != null &&
                gameInfo.HookCode == hp.Hookcode &&
                (gameInfo.ThreadContext & 0xFFFF) == (hp.Ctx & 0xFFFF) &&
                gameInfo.SubThreadContext == hp.Ctx2)
            {
                log.Info(hp.Text);
                SelectedDataEvent?.Invoke(typeof(Textractor), hp);
            }
        }
Example #11
0
        void HandleDataEvent(int channelId, int receivedSize)
        {
#if NETWORK_DEBUGGER_ENABLED
            var logMessage = new System.Text.StringBuilder("ClientPeer");
            logMessage.Append(" Incoming");
            logMessage.Append(" ChannelId:").Append(channelId);
            logMessage.Append(" Size:").Append(receivedSize);

            UnityEngine.Debug.Log(logMessage);
#endif

#if NETWORK_PROFILER_ENABLED && UNITY_EDITOR
            var profilerName = new System.Text.StringBuilder("ClientPeer");
            profilerName.Append(channelId);
            Profiler.NetworkProfiler.RecordChannelIncoming(profilerName.ToString(), (ushort)receivedSize);
#endif
            if (DataEvent != null)
            {
                DataEvent.Invoke(channelId, m_RecievedBuffer, receivedSize);
            }
        }
Example #12
0
 public static void InsertHook(string hookcode)
 {
     // 重复插入相同的code(可能)会导致产生很高位的Context
     foreach (var v in ThreadHandleDict)
     {
         if (hookcode == v.Value.Hookcode)
         {
             DataEvent?.Invoke(typeof(Textractor), new HookParam
             {
                 Name     = "控制台",
                 Hookcode = "HB0@0",
                 Text     = "ErogeHelper: 该特殊码已插入"
             });
             return;
         }
     }
     foreach (Process p in DataRepository.GameProcesses)
     {
         TextHostLib.InsertHook((uint)p.Id, hookcode);
         log.Info($"Try insert code {hookcode} to PID {p.Id}");
     }
 }
Example #13
0
        void HandleData(int connectionId, int channelId, int receivedSize, NetworkError error)
        {
            var client = FindConnection(connectionId);

            if (client == null)
            {
                return;
            }

            client.LastError = error;

#if NETWORK_DEBUGGER_ENABLED
            UnityEngine.Debug.Log($"ServerPeer Incoming : ConnectionId:{connectionId}, Size:{receivedSize}");
#endif

#if NETWORK_PROFILER_ENABLED && UNITY_EDITOR
            var profilerName = new StringBuilder(PROFILER_CATEGORY_PREFIX);
            profilerName.Append(channelId);
            NetworkProfiler.RecordChannelIncoming(profilerName.ToString(), (ushort)receivedSize);
#endif

            DataEvent?.Invoke(client, channelId, m_RecievedBuffer, receivedSize);
        }
Example #14
0
        /// <summary>
        /// Returns the current status of listener
        /// </summary>
        /// <returns></returns>
        public bool StartListener()
        {
            if (IsListening)
            {
                return(IsListening);
            }
            IPAddress serverIP = IPAddress.Parse(Services.CommonUtility.GetIPAddress());

            listener = new TcpListener(serverIP, Port);

            try
            {
                listener.Start();
                IsListening = true;
            }
            catch (Exception ex)
            {
                IsListening = false;
                ExceptionHandler?.Invoke(null, ex);
                return(IsListening);
            }

            Task.Run(async() =>
            {
                while (IsListening)
                {
                    try
                    {
                        ReplyPacket replyPacket = new ReplyPacket()
                        {
                            IsSentAndReplyReceived = true
                        };
                        TcpClient clientTCP    = await listener.AcceptTcpClientAsync().ConfigureAwait(false);
                        replyPacket.PortSender = ((IPEndPoint)clientTCP.Client.RemoteEndPoint).Port;
                        replyPacket.IPSender   = ((IPEndPoint)clientTCP.Client.RemoteEndPoint).Address.ToString();
                        if (ReceiveFromThisIPAddressList.Count > 0)
                        {
                            bool isProcessingRequired = false;
                            foreach (var ipAcceptable in ReceiveFromThisIPAddressList)
                            {
                                if (ipAcceptable == replyPacket.IPSender)
                                {
                                    isProcessingRequired = true;
                                    break;
                                }
                            }
                            if (!isProcessingRequired)
                            {
                                continue;
                            }
                        }

                        int length;
                        NetworkStream stream     = clientTCP.GetStream();
                        List <byte> singlePacket = new List <byte>();
                        var byteArray            = new byte[1024];
                        while ((length = stream.Read(byteArray, 0, byteArray.Length)) != 0)
                        {
                            var copy = new byte[length];
                            Array.Copy(byteArray, 0, copy, 0, length);
                            singlePacket.AddRange(copy);
                        }
                        replyPacket.SetReply(singlePacket);
                        DataEvent?.Invoke(this, replyPacket);
                        if (IsAutoReplying)
                        {
                            await stream.WriteAsync(AutoReply?.ToArray(), 0, AutoReply.Count).ConfigureAwait(false);
                            stream.Flush();
                        }
                        stream.Close();
                        clientTCP.Close();
                    }
                    catch (Exception ex)
                    {
                        ExceptionHandler?.Invoke(this, ex);
                    }
                }
                listener.Server.Close();
            });
            return(IsListening);
        }
        /// <summary>
        /// Decodes and routes an event.
        /// </summary>
        /// <param name="element">The element.</param>
        protected void DecodeAndRouteEvent(XElement element)
        {
            if (element.Name == XName.Get("json"))
            {
                try
                {
                    var eventTypeElement = element.Element("type");
                    if (eventTypeElement == null)
                    {
                        return;
                    }

                    var eventDataElement = element.Element("data");
                    if (eventDataElement == null)
                    {
                        return;
                    }

                    var eventType = eventTypeElement
                                    .Nodes()
                                    .OfType <XCData>()
                                    .FirstOrDefault()
                                    .Value;
                    var eventData = eventDataElement
                                    .Nodes()
                                    .OfType <XCData>()
                                    .FirstOrDefault()
                                    .Value;

                    var eventBytes       = System.Text.Encoding.UTF8.GetBytes(eventData);
                    var dictionaryReader = JsonReaderWriterFactory.CreateJsonReader(
                        eventBytes, 0, eventBytes.Length, new XmlDictionaryReaderQuotas());

                    var fabricator = SchemaFabricator;
                    if (fabricator != null)
                    {
                        var fabricatorType = fabricator.GetType(eventType);
                        if (fabricatorType != null)
                        {
                            if (DataEvent != null)
                            {
                                var serializer = new DataContractJsonSerializer(fabricatorType);
                                var trueEntity = serializer.ReadObject(dictionaryReader);
                                DataEvent.Invoke(trueEntity);
                            }

                            return;
                        }
                    }

                    if (XmlEvent != null)
                    {
                        var dictionaryDocument = XDocument.Load(dictionaryReader);
                        dictionaryDocument.Root.Name = eventType;
                        XmlEvent.Invoke(dictionaryDocument.Root);
                    }
                }
                catch (EPException e)
                {
                }
            }
            else if (element.Name == XName.Get("xml"))
            {
                if (XmlEvent != null)
                {
                    XmlEvent.Invoke(element.Elements().FirstOrDefault());
                }
            }
            else if (element.Name == XName.Get("map"))
            {
                DictionaryEvent(
                    element.Attribute("name").Value,
                    element.Elements().FirstOrDefault().ToDictionary());
            }
            else
            {
                throw new ArgumentException(string.Format("Content type \"{0}\" is not recognized", element.Name));
            }
        }
 public void OnEventRaised(EventData eventData)
 {
     dataResponse.Invoke(eventData);
 }
Example #17
0
        public void operate(string type, string msg = "")
        {
            ThreadStart action = null;

            stateTitle = "";
            if (type == "init")
            {
                if (hwnd > 0)
                {
                    unbind();
                }
                action = () =>
                {
                    try
                    {
                        Thread.Sleep(3000);
                        init_window(int.Parse(msg));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                };
            }
            else if (type == "locate")
            {
                action = () =>
                {
                    locate(msg, setting.AutoTrans);
                };
            }
            else if (type == "shout")
            {
                action = () =>
                {
                    shout(msg);
                };
            }
            else if (type == "pause")
            {
                action = () =>
                {
                    setState("已暂停");
                };
            }
            else if (type == "screenshot")
            {
                action = () =>
                {
                    screenshot(new Random().Next() + ".bmp");
                };
            }
            else if (type == "fuhun-init")
            {
                stateTitle = "附魂";
                action     = () =>
                {
                    setState("报名中");
                    fuhun.Sign();
                    setState("准备竞技");
                    //findMap("中立-附魂战场");
                    DataEvent?.Invoke("fuhun-capture", fuhun.GetCapture());
                    setState("标记敌人中");
                    //DataEvent?.Invoke("fuhun-capture", @"E:\Users\Administrator\source\repos\WpfApp1\MyTool\bin\Debug\debug\fuhun\637159218502426004.bmp");
                };
            }
            else if (type == "fuhun-tag")
            {
                stateTitle = "附魂";
                action     = () =>
                {
                    setState("PK中");
                    fuhun.PK(msg);
                    DataEvent?.Invoke("fuhun-end", "");
                };
            }
            else if (type == "fight")
            {
                stateTitle = "打架";
                action     = () => fight.Action(msg);
            }
            else if (type == "kuafu-boss")
            {
                stateTitle = "跨服boss";
                action     = () => kuafuBoss.Action(msg);
            }
            else if (type == "game-setting")
            {
                setting = JsonConvert.DeserializeObject <GameSetting>(msg);
            }
            if (action != null)
            {
                killTask();
                thread = new Thread(action);
                thread.Start();
            }
        }
Example #18
0
 public void Invoke()
 {
     dataEvent.Invoke(data);
 }
 private void Fire_DataEvent(string Data, DataDirection Direction)
 {
     DataEvent?.Invoke(Data, Direction);
 }
Example #20
0
        private void loop()
        {
            byte ch = (byte)this._port.ReadByte();

            if (_index == 0)
            {
                _frame.Clear();
            }
            else
            {
                _frame.Add(ch);
            }

            switch (_index)
            {
            case 0:
                if (ch != 0x42)
                {
                    return;
                }
                _calculatedChecksum = ch;
                break;

            case 1:
                if (ch != 0x4D)
                {
                    _index = 0;
                    return;
                }
                _calculatedChecksum += ch;
                break;

            case 2:
                _calculatedChecksum += ch;
                _frameLen            = (ushort)(ch << 8);
                break;

            case 3:
                _frameLen |= ch;
                if (_frameLen != 2 * 9 + 2 && _frameLen != 2 * 13 + 2)
                {
                    _index = 0;
                    return;
                }
                _calculatedChecksum += ch;
                break;

            default:
                if (_index == _frameLen + 2)
                {
                    _checksum = (ushort)(ch << 8);
                }
                else if (_index == _frameLen + 2 + 1)
                {
                    _checksum |= ch;

                    if (_calculatedChecksum == _checksum)
                    {
                        FeedbackEvent?.Invoke(this, new RawDataEventArgs("< " + string.Join(" ", _frame.Select(c => ((byte)c).ToString("X2")))));
                        DataEvent?.Invoke(this, new DataEventArgs(_payload));
                    }

                    _index = 0;
                    return;
                }
                else
                {
                    _calculatedChecksum += ch;
                    byte payloadIndex = (byte)(_index - 4);

                    if (payloadIndex < _payload.Length)
                    {
                        _payload[payloadIndex] = ch;
                    }
                }
                break;
            }
            _index++;
        }