Esempio n. 1
0
        public static void CharacterSelect(byte[] packet, SocketClient sockstate)
        {
            String Name;
            int CID = 0;
            bool loginsuccess = true;

            CMSG_CHARACTER_SELECT cpkt = (CMSG_CHARACTER_SELECT)packet;
            Name = cpkt.Name;

            foreach(Mobile character in sockstate.Account.Characters)
            {
                if (character.Name == Name)
                {
                    CID = character.CID;
                    loginsuccess = true;
                }
            }

            if (loginsuccess == true)
            {
                SMSG_CHARACTER_SELECT spkt = new SMSG_CHARACTER_SELECT(Name);
                sockstate.Client.PacketQueue.Enqueue(spkt.Stream);

                SMSG_CHANNEL_SLIME slimePkt = new SMSG_CHANNEL_SLIME();
                sockstate.Client.PacketQueue.Enqueue(slimePkt.Stream);

                sockstate.SelectedChar = CID;
            }
            else
            {
                Logger.Log(Logger.LogLevel.Error, "Hack Detection", "Account: {0} - Invalid Select Character Name: {1}", sockstate.Account.Username, Name);
                sockstate.Disconnect();
            }
        }
Esempio n. 2
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            SocketClient client = new SocketClient();
            string resposta;
            client.Connect("10.20.2.124", 6654);
            client.Send("nomejogador/" + txtblock1.Text + "/" + txtblock2.Text);
            resposta = client.Receive();
            /*if (resposta.StartsWith("<ERRO>"))
            {
                MessageBox.Show(resposta);
            }*/

            if (resposta == "naocadastrado")
            {
                MessageBox.Show("Cliente não cadastrado ou senha inválida!");
            }
            else if (resposta == "naook")
            {
                MessageBox.Show("Cliente já está logado no sistema!");
            }
            else
            {
                NavigationService.Navigate(new Uri("/Menu.xaml", UriKind.RelativeOrAbsolute));
            }

        }
Esempio n. 3
0
        internal void Initialize(SocketClient client, TcpClient tcpClient)
        {
            this.client = client;
            this.tcpClient = tcpClient;

            this.onInitialize ();
        }
        public static void Handel(SocketClient client, ForgotPasswordRequest request)
        {
            var reply = new LoginResponse();
            try
            {
                var user = AccountRepository.GetAccount(null, request.Email);
                if (user != null)
                {
                    if (user.Locked)
                        reply.ResponseType = LoginResponseType.AccountLocked;

                    else if (user.Verified)
                    {
                        user.Locked = true;
                        user.Verified = false;
                        user.Verificationcode = Guid.NewGuid().ToString();
                        reply.AccountId = user.Accountid;
                        reply.ResponseType = LoginResponseType.ResetSent;
                        EmailSender.SendRestEmail(user);
                        BaseRepository.Update(user);
                    }
                    else
                        reply.ResponseType = LoginResponseType.AccountNotVerified;
                }
                else
                    reply.ResponseType = LoginResponseType.ResetInvalid;

            }
            catch (Exception e)
            {
                reply.ResponseType = LoginResponseType.DatabaseError;
                Logger.Error(e.Message);
            }
            client.Send(reply);
        }
Esempio n. 5
0
 /// <summary>
 /// Called when the packet is sent.
 /// </summary>
 /// <param name="p">The packet that was sent.</param>
 public void SentPacket(Packet p, SocketClient client)
 {
     lock (syncSentPackets)
     {
         sentPackets.AddLast(new PacketSenderPair(p, client));
     }
 }
 public void IsConnectedTest()
 {
     SocketClient target = new SocketClient(); // TODO: 初始化为适当的值
     bool actual;
     actual = target.IsConnected;
     Assert.Inconclusive( "验证此测试方法的正确性。" );
 }
        public static void Login(byte[] packet, SocketClient sockstate)
        {
            String Username;
            String Password;

            CMSG_ACCOUNT_LOGIN cpkt = (CMSG_ACCOUNT_LOGIN)packet;
            Username = cpkt.Username;
            Password = cpkt.Password;

            Regex countPattern = new Regex("NHN_P_LOGIN=(.+);");
            Match m1 = countPattern.Match(Password);
            Password = m1.Groups[1].ToString();

            // authenticate
            SMSG_ACCOUNT_LOGIN accPkt = Database.Login(Username, Password, sockstate);
            sockstate.Account.Username = Username;
            sockstate.Client.PacketQueue.Enqueue(accPkt.Stream);

            if (accPkt.LoginSuccess == true)
            {
                Logger.Log(Logger.LogLevel.Access, "Authentication", "Login accepted for user : {0} ", sockstate.Account.Username);

                // send login options
                SMSG_ACCOUNT_OPTIONS optionsPkt = new SMSG_ACCOUNT_OPTIONS();
                optionsPkt.CharSlot = sockstate.Account.Options;
                optionsPkt.CharUnlock = sockstate.Account.Options;
                sockstate.Client.PacketQueue.Enqueue(optionsPkt.Stream);

                // send character list
                List<Structures.Mobile> Characters = Database.CharacterList(sockstate.Account.AID);
                sockstate.Account.Characters = Characters;
                SMSG_CHARACTER_LIST charlistPkt = new SMSG_CHARACTER_LIST(Characters);
                sockstate.Client.PacketQueue.Enqueue(charlistPkt.Stream);
            }
        }
 public void ConnectHandleManagerTest()
 {
     SocketClient target = new SocketClient(); // TODO: 初始化为适当的值
     ConnectHandleManager actual;
     actual = target.ConnectHandleManager;
     Assert.Inconclusive( "验证此测试方法的正确性。" );
 }
 public static void ChannelPrevious(byte[] packet, SocketClient sockstate)
 {
     List<Structures.Mobile> Characters = Database.CharacterList(sockstate.Account.AID);
     sockstate.Account.Characters = Characters;
     SMSG_CHARACTER_LIST charlistPkt = new SMSG_CHARACTER_LIST(Characters);
     sockstate.Client.PacketQueue.Enqueue(charlistPkt.Stream);
 }
        public static void ChannelSelect(byte[] packet, SocketClient sockstate)
        {
            CMSG_CHANNEL_SELECT cpkt = (CMSG_CHANNEL_SELECT)packet;
            String SqrName = cpkt.SqrName;

            lock (Program.SquareList)
            {
                for (int i = 0; i < Program.SquareList.Count; ++i)
                {
                    if (Program.SquareList[i].Name == SqrName)
                    {
                        SMSG_CHANNEL_SELECT spkt = new SMSG_CHANNEL_SELECT(Program.SquareList[i], sockstate.SelectedChar);
                        SMSG_SEND_SESSION sessionPkt = new SMSG_SEND_SESSION(sockstate.SelectedChar);

                        try
                        {
                            // notify world
                            Program.SquareList[i].Socket.Client.Socket.Send(sessionPkt.Stream);
                        }
                        catch(Exception)
                        {
                            Logger.Log(Logger.LogLevel.Access, "World Server", "Server {0} not responding", Program.SquareList[i].Name);
                            Program.SquareList.RemoveAt(i);
                        }

                        // notify client
                        sockstate.Client.PacketQueue.Enqueue(spkt.Stream);

                        break;
                    }
                }
            }
        }
Esempio n. 11
0
 static SocketManager()
 {
     Stream = new ZYNetBufferReadStreamV2(40960);
     client = new SocketClient();
     client.BinaryInput += new ClientBinaryInputHandler(client_BinaryInput);
     client.ErrorLogOut += new ErrorLogOutHandler(client_ErrorLogOut);
     client.MessageInput += new ClientMessageInputHandler(client_MessageInput);
 }
Esempio n. 12
0
 static SocketManager()
 {
     //初始化数据包缓冲区,并设置了最大数据包尽可能的大 
     BuffListManger = new ZYNetRingBufferPool(400000); 
     client=new SocketClient();
     client.DataOn += new DataOn(client_DataOn);
     client.Disconnection += new ExceptionDisconnection(client_Disconnection);
 }
    /* Unity Lifecyle */
    void Start()
    {
        socketClient = new SocketClient("192.168.1.9", 1234, socketReadCallback);

        if(SOCKET_ACTIVE) {
            socketClient.connect();
        }
    }
Esempio n. 14
0
 public void Connect(string path)
 {
     _path = path;
     if (_client != null &&_client.IsConnected)
         _client.Disconnect();
     _client = null;
     isConnected();
 }
Esempio n. 15
0
        public static void Handle(SocketClient client, LoginResponse response)
        {
            if (response.ResponseType == LoginResponseType.AccountNotVerified)
                EmailSender.SendWelcomeEmail(AccountRepository.GetAccount(response.AccountId));

            if(response.ResponseType == LoginResponseType.AccountInUse)
                Program.OnlineAccounts[response.AccountId].Disconnect();
        }
Esempio n. 16
0
    public u3dclient()
    {



        register_function();
        socket_client = new SocketClient(1048576, 1048576, 131072, null, new MessageHandler(MessageClient),
            new CloseHandler(CloseClient), new ErrorHandler(ErrorClient), new ConnectHandler(on_connect));
    }
        public static void FileHash(byte[] packet, SocketClient sockstate)
        {
            CMSG_CLIENT_HASH cpkt = (CMSG_CLIENT_HASH)packet;
            String Hash = cpkt.Hash;
            Hash = cpkt.Hash;

            // Add version check for future release, assumed correct.
            SMSG_CLIENT_HASH spkt = new SMSG_CLIENT_HASH((int)SMSG_CLIENT_HASH.Result.OK);
            sockstate.Client.PacketQueue.Enqueue(spkt.Stream);
        }
Esempio n. 18
0
        public static void GetSkillList(byte[] packet, SocketClient sockstate)
        {
            byte[] skilllist =
            {
                0x0e, 0x00, 0xe0, 0x55, 0xce, 0x60, 0x52, 0xc0,
                0x3c, 0x39, 0x00, 0x00, 0x00, 0x00
            };

            sockstate.Client.PacketQueue.Enqueue(skilllist);
        }
Esempio n. 19
0
 /// <summary>
 /// Adds a client to the Client List when the client connects to the server. In case a client
 /// already exists with the specified clientId then the old client entry is removed before the adding
 /// the new one.
 /// </summary>
 /// <param name="clientId"> </param>
 public static void AddClientOnConnect(string clientId)
 {
     SocketClient client;
     if(ConnectedClients.ContainsKey(clientId))
     {
         ConnectedClients.TryRemove(clientId, out client);
     }
     client = new SocketClient(clientId);
     ConnectedClients.TryAdd(clientId, client);
 }
Esempio n. 20
0
        private static void Test1(SocketClient client)
        {
            DirectoryService service = client.GetService<DirectoryService> ();
            DirectoryItemInfo directory = service.Get ("/") as DirectoryItemInfo;
            IEnumerable<FileSystemItemInfo> contents = service.GetContents (directory);

            foreach (FileSystemItemInfo content in contents)
                Console.WriteLine (content.Path);

            service.Close ();
        }
Esempio n. 21
0
 public MicrophoneClient(RoomSelected roomselecter)
 {
     this._view = roomselecter;
     _timer.Interval = new TimeSpan(0, 0, 1);
     _timer.Tick += new EventHandler(_timer_Tick);
     _cliente = new SocketClient(roomselecter);
     _microfonos = new List<Microfono>();
     Conectado = ConectarseAServidor();
     if (Conectado)
         ApagarTodos();
 }
Esempio n. 22
0
        static void Main(string[] args)
        {
            var socketClient = new SocketClient(2015, 256);
            socketClient.OnConnectedServer += socketClient_OnConnectedServer;
            socketClient.OnReceiveMessage += socketClient_OnReceiveMessage;
            socketClient.OnDisConnectedServer += socketClient_OnDisConnectedServer;
            socketClient.OnConnectFail += socketClient_OnConnectFail;
            socketClient.StartClient();

            Console.ReadLine();
        }
Esempio n. 23
0
        public static void CreateCharacter(byte[] packet, SocketClient sockstate)
        {
            String Name;
            int Class;

            CMSG_CHARACTER_CREATE cpkt = (CMSG_CHARACTER_CREATE)packet;
            Name = cpkt.Name;
            Class = cpkt.Class;

            SMSG_CHARACTER_CREATE spkt = Database.CharacterCreate(Name, Class, sockstate.Account.AID);
            sockstate.Client.PacketQueue.Enqueue(spkt.Stream);
        }
 public void InitClient()
 {
     SocketCallBack callback = new SocketCallBack();
     callback.callback += GetServerMessage;
     DemoCMDProcess process = new DemoCMDProcess( callback );
     this.dispatcher = new SocketEventDispatcher( process );
     this.client = new SocketClient();
     this.client.SocketMessageReceivedFromServer += new System.EventHandler<SocketMessageReceivedFromServer>( this.OnReceiveMessageFromServer );
     this.client.CreateConnectCompleted += new EventHandler<CreateConnectionAsyncArgs>( this.OnCreateConnectionComplete );
     this.client.CloseHandler += new EventHandler( this.CloseHandler );
     this.client.ConnectError += new EventHandler( this.ConnectError );
 }
Esempio n. 25
0
 public void CloseConnect(SocketClient c, bool remove=false)
 {
     if (c == null)
     {
         return;
     }
     log.InfoFormat("Device {0} closed.", c.IpAddr );
     c.Close();
     if (remove)
     {
         SocketClient removed;
         _connections.TryRemove(c.IpAddr, out removed);
     }
 }
        public SMSG_BAG_INFO(SocketClient sockstate)
            : base(64141)
        {
            this.EnsureCapacity(256);

            // BagState
            // BagNumber
            // ExpireDate

            // 30 00 E0 55 8D FA CC E1 3C 39 01 00 00 00 62 53  0.àU.úIá<9....bS
            // A9 DA 02 00 00 00 AF D5 69 17 0F 27 01 00 01 00  cU...._Oi..'....
            // 00 00 00 00 00 00 00 00 E9 CD 3C 39 00 00 00 00  ........éI<9....

            HashArray hArray = new HashArray((int)Hash.Bag, sockstate.Character.BagCount);
        }
Esempio n. 27
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="fullData"></param>
 public void QueuePacket(byte[] fullData, SocketClient receiver)
 {
     PacketReceiverPair pair = PacketReceiverPair.empty;
     try
     {
         this.receivedPackets.AddLast((pair = new PacketReceiverPair(fullData, receiver)));
     }
     catch (NullReferenceException e)
     {
         Console.Error.WriteLine("QueuePacket got a nullpointer!");
         // if (pair.Equals( null )) Console.Error.WriteLine("Pair was null");
         if (fullData == null) Console.Error.WriteLine("fullData was null!");
         if (receiver == null) Console.Error.WriteLine("receiver was null!");
     }
 }
Esempio n. 28
0
        public static void GetInventory(byte[] packet, SocketClient sockstate)
        {
            byte[] inventory =
            {
                0x32, 0x00, 0xe0, 0x55, 0x60, 0x72, 0x10, 0x00,
                0x58, 0x00, 0x58, 0x00, 0x58, 0x00, 0x58, 0x00,
                0x58, 0x00, 0x58, 0x00, 0x58, 0x00, 0x58, 0x00,
                0x58, 0x00, 0x58, 0x00, 0x58, 0x00, 0x58, 0x00,
                0x58, 0x00, 0x58, 0x00, 0x58, 0x00, 0x00, 0x00,
                0x4f, 0x42, 0x9e, 0x52, 0x06, 0xa1, 0x30, 0x03,
                0x00, 0x00
            };

            sockstate.Client.PacketQueue.Enqueue(inventory);
        }
Esempio n. 29
0
        public static void Handshake(byte[] packet, SocketClient sockstate)
        {
            var handshake = (HANDSHAKE)(packet);

            var major = handshake.Body["major"].AsInt32();
            var minor = handshake.Body["minor"].AsInt32();
            var patch = handshake.Body["patch"].AsInt32();

            Debugger.Log("SERVER PROTOCOL: v{0}.{1}.{2}", major, minor, patch);

            if (handshake.Body["success"].AsBoolean()) {
                Debugger.Log("HANDSHAKE_OK");
            } else {
                Debugger.Log("HANDSHAKE_FAILED");
            }
        }
Esempio n. 30
0
        public static void ConnectWorld(byte[] packet, SocketClient sockstate)
        {
            CMSG_CONNECT_MASTER cpkt = (CMSG_CONNECT_MASTER)packet;

            string Name = cpkt.Name;
            string IPAddr = cpkt.IPAddr;
            int Port = cpkt.Port;

            Square nSquare = new Square(Name, 1, 0, IPAddr, Port, sockstate);
            Program.SquareList.Add(nSquare);

            Logger.Log(Logger.LogLevel.Access, "Client.World", "World server connected : {0} ", Name);

            sockstate.WServer = true;
            sockstate.WSquare = nSquare;
        }
        /// <summary>
        /// Retreives the localization data of the selected node from the controller
        /// </summary>
        private void GetLocData()
        {
            //static part of the message
            string xml_send = @"<?xml version=""1.0"" standalone=""yes""?><Requests xmlns:xsi=""='http://www.w3.org/2001/XMLSchema-instance'""  xmlns=""xmlns='http://tempuri.org/Requests.xsd\'""><Request><RequestName>getnodeLocInfo</RequestName>";

            //return the nodeid with sensor as input
            try
            {
                string selected = listBoxLoc.SelectedItem.ToString();
                if (selected != null)
                {
                    string nodeid;
                    nodeid = getNodeID(selected);

                    xml_send += "<arg>" + nodeid + "</arg></Request></Requests>";

                    SocketClient socket_client = new SocketClient(Port, controllerIP.Text);
                    // Receiving data
                    string xml_receive = socket_client.Connect(xml_send, true);


                    XmlDocument tempdoc = new XmlDocument();
                    tempdoc.LoadXml(xml_receive);

                    XmlNodeList bookList = tempdoc.GetElementsByTagName("Position");
                    foreach (XmlNode node in bookList)
                    {
                        XmlElement ID = (XmlElement)(node);
                        try
                        {
                            textBoxNodeID.Text  = ID.GetElementsByTagName("node")[0].InnerText;
                            textBoxANodeID.Text = getTelosbId(ID.GetElementsByTagName("ANode")[0].InnerText);
                            textBoxRSSI.Text    = ID.GetElementsByTagName("RSSI")[0].InnerText;
                            textBoxX.Text       = ID.GetElementsByTagName("X")[0].InnerText;
                            textBoxY.Text       = ID.GetElementsByTagName("Y")[0].InnerText;

                            try
                            {
                                int index = ID.GetElementsByTagName("Time")[0].InnerText.IndexOf(' ');
                                textBoxLocUpdate.Text = ID.GetElementsByTagName("Time")[0].InnerText.Substring(index);
                            }
                            catch
                            {
                                Console.WriteLine("No time available for loc info");
                            }

                            try
                            {
                                textBoxZ.Text = ID.GetElementsByTagName("Z")[0].InnerText;
                            }
                            catch
                            {
                                textBoxZ.Text = "N/A";
                            }
                        }
                        catch
                        {
                            Console.WriteLine("Some field is not available");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.TargetSite);
            }
        }
Esempio n. 32
0
        public void Handle(byte[] Data, SocketClient Client)
        {
            byte WHKey;

            if (!Kernel.WarehouseKeys.TryGetValue(Client.Character.MapID, out WHKey))
            {
                return;
            }
            byte Type = Data[8];

            switch (Type)
            {
            case 0:
            {
                ConcurrentBag <Items.Item> WHItems;
                if (Client.Character.Warehouses.TryGetValue(Client.Character.MapID, out WHItems))
                {
                    Client.Send(Packets.ToSend.ViewWarehouse(Client.Character.CurrentDialog.ActiveNPC, WHItems));
                }
                else
                {
                    Client.Send(Packets.ToSend.ViewWarehouse(Client.Character.CurrentDialog.ActiveNPC));
                }
                break;
            }

            case 1:
            {
                uint       ItemUID = BitConverter.ToUInt32(Data, 12);
                Items.Item Item;
                if (!Client.Character.Inventory.Items.TryGetValue(ItemUID, out Item))
                {
                    return;
                }
                ConcurrentBag <Items.Item> WHItems;
                if (!Client.Character.Warehouses.TryGetValue(Client.Character.MapID, out WHItems))
                {
                    WHItems = new ConcurrentBag <Items.Item>();
                    Client.Character.Warehouses.TryAdd(Client.Character.MapID, WHItems);
                }
                byte MaxSlots = 20;
                if (Client.Character.MapID == 1036)
                {
                    MaxSlots = 40;
                }
                if (WHItems.Count >= MaxSlots)
                {
                    return;
                }
                Client.Character.Inventory.Remove(ItemUID);
                Item.Position = WHKey;
                WHItems.Add(Item);
                if (WHItems.Count == 21)
                {
                    Client.Send(Packets.ToSend.AddWHItem(Client.Character.CurrentDialog.ActiveNPC, Item));
                }
                Client.Send(Packets.ToSend.ViewWarehouse(Client.Character.CurrentDialog.ActiveNPC, WHItems));
                break;
            }

            case 2:
            {
                uint ItemUID = BitConverter.ToUInt32(Data, 12);
                ConcurrentBag <Items.Item> WHItems;
                if (!Client.Character.Warehouses.TryGetValue(Client.Character.MapID, out WHItems))
                {
                    return;
                }
                foreach (Items.Item I in WHItems)
                {
                    if (I.UniqueID == ItemUID)
                    {
                        Items.Item removedItem;
                        if (WHItems.TryTake(out removedItem))
                        {
                            Client.Send(Packets.ToSend.ViewWarehouse(Client.Character.CurrentDialog.ActiveNPC, WHItems));
                            removedItem.Position = 0;
                            Client.Character.Inventory.TryAdd(removedItem);
                            Client.Send(removedItem.ToBytes);
                        }
                        return;
                    }
                }
                break;
            }

            default: Console.WriteLine("Missing Warehouse Packet: " + Type); break;
            }
        }
Esempio n. 33
0
        public void SetDataByRoomId(DataSet ds, bool isFromTimer)
        {
            try
            {
                if (ds != null && ds.Tables.Count > 0)
                {
                    if (ds.Tables["Room"] != null && ds.Tables["Room"].Rows.Count > 0)
                    {
                        Room room = new Room(Ap.Cxt, ds.Tables["Room"].Rows[0]);

                        if (!string.IsNullOrEmpty(room.TournamentID.ToString()))
                        {
                            Ap.SelectedRoomParentID = room.ParentID;
                            Ap.RoomTournamentID     = room.TournamentID;

                            isUrlBit = room.IsUrlBit;
                            url      = string.Empty;
                            if (isUrlBit)
                            {
                                if (DBNull.Value.ToString() != room.Html &&
                                    room.Html != string.Empty)
                                {
                                    url = room.Html;
                                }
                            }

                            if (LoadRoomInfoPage != null && !isFromTimer)
                            {
                                LoadRoomInfoPage(Ap.SelectedRoomID, Ap.RoomTournamentID, url);
                            }
                        }
                    }

                    if (ds.Tables["LoggedinUsers"].Rows.Count > 0)
                    {
                        if (!string.IsNullOrEmpty(ds.Tables["LoggedinUsers"].Rows[0]["LoggedinUser"].ToString()))
                        {
                            tsUserCounter.Text = ds.Tables["LoggedinUsers"].Rows[0]["LoggedinUser"].ToString();
                        }
                    }

                    if (ds.Tables.Count == 0)
                    {
                        return;
                    }

                    if (LoadPlayerGrid != null)
                    {
                        LoadPlayerGrid(ds.Tables["Users"]);
                    }

                    if (LoadGameGrid != null)
                    {
                        LoadGameGrid(ds.Tables["Games"]);
                    }

                    if (LoadChallengeGrid != null)
                    {
                        LoadChallengeGrid(ds.Tables["Challenges"]);
                    }

                    if (LoadUserMessages != null)
                    {
                        if (ds.Tables["UserMessages"] != null)
                        {
                            LoadUserMessages(ds.Tables["UserMessages"]);
                        }
                    }

                    if (ds.Tables["RoomUsersCount"] != null)
                    {
                        if (ds.Tables["RoomUsersCount"].Rows.Count > 0)
                        {
                            if (treeView1.Nodes.Count > 0)
                            {
                                SetRoomUsersCount(ds);
                            }
                        }
                    }

                    if (ds.Tables["AcceptedChallenge"] != null)
                    {
                        if (ds.Tables["AcceptedChallenge"].Rows.Count > 0)
                        {
                            int challengeID = UData.ToInt32(ds.Tables["AcceptedChallenge"].Rows[0]["ChallengeID"]);
                            InfinityChess.WinForms.MainOnline.ShowMainOnline(challengeID, ChallengeStatusE.Accepted, 0);
                            Ap.CanAutoChallenge = true;
                            return;
                        }
                    }

                    //Only for human tounament rooms
                    if (Ap.SelectedRoomID > (int)RoomE.EngineTournaments && Ap.SelectedRoomParentID != (int)RoomE.ComputerChess && Ap.SelectedRoomParentID != (int)RoomE.EngineTournaments)
                    {
                        if (Ap.IsGameInProgress || Ap.KibitzersCount > 0)
                        {
                            return;
                        }

                        Ap.CurrentUser.UserStatusIDE = UserStatusE.Blank;
                        Ap.CurrentUser.EngineID      = 1;

                        Ap.PlayingMode.ChessTypeID           = 1;
                        PlayingModeData.Instance.ChessTypeID = 1;

                        if (Ap.PlayingMode.SelectedEngine != null)
                        {
                            Ap.PlayingMode.SelectedEngine.Close();
                            Ap.PlayingMode.SelectedEngine = null;
                        }

                        SocketClient.SetUserEngine(string.Empty, Ap.CurrentUser.UserStatusIDE);
                    }

                    return;
                }
                else
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                TestDebugger.Instance.WriteError(ex);
            }
        }
Esempio n. 34
0
 private void SendFunc(SocketClient client)
 {
     client.Send();
 }
        /// <summary>
        /// Occurs when the apply changes button is click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonWSNControl_Click(object sender, EventArgs e)
        {
            //TODO: needs validation;
            panelControl.Enabled     = false;
            buttonWSNControl.Enabled = false;

            //we send the WSNactionRequest here
            //first
            //static part of the message
            string xml_send = @"<?xml version=""1.0"" standalone=""yes""?><WSNReq xmlns:xsi=""='http://www.w3.org/2001/XMLSchema-instance'""  xmlns=""xmlns='http://tempuri.org/Requests.xsd\'""><WSNReq><RequestAction>";

            //return the nodeid with sensor as input
            try
            {
                string selected = listBoxControl.SelectedItem.ToString();
                string nodeid;
                nodeid    = getNodeID(selected);
                xml_send += "<NodeID>" + nodeid + "</NodeID>";

                //secondly we must check which fields have changed
                //we can then add them ass nodes in the XML

                //specific to our localization scheme
                if (oldChanges.Active != ActiveProperty)
                {
                    xml_send += "<active>" + ActiveProperty + "</active>";
                }
                //only process these parameters if the node is active in the localization algorithm
                if (ActiveProperty == "1")
                {
                    if (oldChanges.AN != AnchorProperty)
                    {
                        xml_send += "<AN>" + AnchorProperty + "</AN>";
                    }
                    //only process these parameters if the node is an Anchor Node
                    if (AnchorProperty == "0")
                    {
                        if (oldChanges.X != textBoxControlX.Text)
                        {
                            xml_send += "<X>" + textBoxControlX.Text + "</X>";
                        }
                        if (oldChanges.Y != textBoxControlY.Text)
                        {
                            xml_send += "<Y>" + textBoxControlY.Text + "</y>";
                        }
                        if (oldChanges.locrate != textBoxLocRate.Text)
                        {
                            xml_send += "<LocRate>" + textBoxLocRate.Text + "</LocRate>";
                        }
                    }
                }

                //telosb general parameters
                //all independent
                if (oldChanges.samplerate != textBoxSampleRate.Text)
                {
                    xml_send += "<Samplerate>" + textBoxSampleRate.Text + "</Samplerate>";
                }
                if (oldChanges.leds != LedsProperty)
                {
                    xml_send += "<Leds>" + LedsProperty + "</Leds>";
                }
                if (oldChanges.power != PowerProperty)
                {
                    xml_send += "<Power>" + PowerProperty + "</Power>";
                }
                if (oldChanges.frequency != FrequencyProperty)
                {
                    xml_send += "<Frequency>" + FrequencyProperty + "</Frequency>";
                }

                xml_send += "</RequestAction></WSNReq></WSNReq>";

                //we can now send the request, we will receive a status message as a response
                SocketClient socket_client = new SocketClient(Port, controllerIP.Text);
                // Sends: ActionRequest
                // Receives: Status
                string xml_receive = socket_client.Connect(xml_send, true);

                XmlDocument tempdoc = new XmlDocument();
                tempdoc.LoadXml(xml_receive);

                XmlNodeList bookList = tempdoc.GetElementsByTagName("Status");
                foreach (XmlNode node in bookList)
                {
                    XmlElement ID = (XmlElement)(node);
                    try
                    {
                        if (
                            ActiveProperty == ID.GetElementsByTagName("active")[0].InnerText &&
                            AnchorProperty == ID.GetElementsByTagName("AN")[0].InnerText &&
                            textBoxControlX.Text == ID.GetElementsByTagName("X")[0].InnerText &&
                            textBoxControlY.Text == ID.GetElementsByTagName("Y")[0].InnerText &&
                            textBoxSampleRate.Text == ID.GetElementsByTagName("Samplerate")[0].InnerText &&
                            textBoxLocRate.Text == ID.GetElementsByTagName("LocRate")[0].InnerText &&
                            LedsProperty == ID.GetElementsByTagName("Leds")[0].InnerText &&
                            PowerProperty == ID.GetElementsByTagName("Power")[0].InnerText &&
                            FrequencyProperty == ID.GetElementsByTagName("Frequency")[0].InnerText)
                        {
                            //WSN Succesfully replied to our request
                            //changes struct
                            oldChanges.Active     = ActiveProperty;
                            oldChanges.AN         = AnchorProperty;
                            oldChanges.X          = textBoxControlX.Text;
                            oldChanges.Y          = textBoxControlY.Text;
                            oldChanges.samplerate = textBoxSampleRate.Text;
                            oldChanges.locrate    = textBoxLocRate.Text;
                            oldChanges.power      = PowerProperty;
                            oldChanges.frequency  = FrequencyProperty;
                            oldChanges.conn       = textBoxConn.Text;
                            oldChanges.leds       = LedsProperty;

                            Console.WriteLine("WSN succesfully replied");
                            MessageBox.Show("WSN succesfully replied");
                        }
                        else
                        {
                            //WSN did NOT! Succesfully replied to our request
                            //roll back to previous state;
                            ActiveProperty         = oldChanges.Active;
                            AnchorProperty         = oldChanges.AN;
                            textBoxControlX.Text   = oldChanges.X;
                            textBoxControlY.Text   = oldChanges.Y;
                            textBoxSampleRate.Text = oldChanges.samplerate;
                            textBoxLocRate.Text    = oldChanges.locrate;
                            FrequencyProperty      = oldChanges.power;
                            FrequencyProperty      = oldChanges.frequency;
                            textBoxConn.Text       = oldChanges.conn;
                            LedsProperty           = oldChanges.leds;

                            Console.WriteLine("WSN did not succesfully reply");
                            MessageBox.Show("WSN did not succesfully reply");
                        }
                    }
                    catch
                    {
                        Console.WriteLine("Some field is not available");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.TargetSite);
            }

            panelControl.Enabled     = true;
            buttonWSNControl.Enabled = true;
        }
 public override void handle(SocketClient <DataHolder> socketClient, ServerInfo serverInfo, DispatchJobEvent @event)
 {
     this.JobExecutor.executeJob(@event.JobId, @event.JobFunctionKey, serverInfo);
 }
Esempio n. 37
0
 private static void CustomHeader(SocketClient a, string msg, string header)
 {
     WriteLine("Bytes received from server with header = " + header + " and message = " + msg);
 }
        /// <summary>
        /// Moves player
        /// </summary>
        /// <param name="i_dir">Movement vector</param>
        /// <param name="i_player">Player name</param>
        public async Task <ServerResponseInfo <bool, Exception> > PlayerMovesAsync(int[] i_dir, string i_player)
        {
            ServerResponseInfo <bool, Exception> response = new ServerResponseInfo <bool, Exception>();

            response.info = true;
            try
            {
                //Gets "gamesession" from StateManager
                GameSession gameSession = await this.StateManager.GetStateAsync <GameSession>("gamesession");

                //Moves player
                MovementResult result = gameSession.MovePlayer(i_dir, i_player);
                //If player wasn't connected
                if (result.type.Equals(MovementResultType.PlayerNotConnected))
                {
                    response.info = false;
                    //Saves "gamesession" state
                    await this.StateManager.SetStateAsync("gamesession", gameSession);
                }
                //If something happened
                else if (!result.type.Equals(MovementResultType.Nothing))
                {
                    //If player died
                    if (result.type.Equals(MovementResultType.PlayerDied))
                    {
                        List <string> message = new List <string>();
                        message.Add("PlayerDead");
                        message.Add(i_player.SerializeObject());
                        message.Add(result.playerPos.SerializeObject());
                        message.Add(DeathReason.Hole.SerializeObject());
                        foreach (string player in gameSession.playerList)
                        {
                            SocketClient socket = new SocketClient();
                            socket.StartGameSessionClient(gameSession.GetPlayerAddress(player), message.SerializeObject() + "<EOF>");
                        }
                    }
                    //If player killed other player
                    else
                    {
                        List <string> message = new List <string>();
                        message.Add("PlayerKilled");
                        message.Add(result.killedPlayer.SerializeObject());
                        message.Add(i_player.SerializeObject());
                        message.Add(result.playerPos.SerializeObject());
                        message.Add(DeathReason.PlayerSmash.SerializeObject());
                        foreach (string player in gameSession.playerList)
                        {
                            SocketClient socket = new SocketClient();
                            socket.StartGameSessionClient(gameSession.GetPlayerAddress(player), message.SerializeObject() + "<EOF>");
                        }
                    }
                    //If there's only one player alive
                    if (gameSession.AlivePlayers().Count == 1)
                    {
                        try
                        {
                            await this.UnregisterReminderAsync(GetReminder("TurretAim"));
                        }
                        catch (Exception e)
                        { }
                        try
                        {
                            await this.UnregisterReminderAsync(GetReminder("TurretShot"));
                        }
                        catch (Exception e)
                        { }
                        List <string> message = new List <string>();
                        message.Add("GameFinished");
                        message.Add(gameSession.AlivePlayers()[0].SerializeObject());
                        foreach (string player in gameSession.playerList)
                        {
                            SocketClient socket = new SocketClient();
                            socket.StartGameSessionClient(gameSession.GetPlayerAddress(player), message.SerializeObject() + "<EOF>");
                        }
                        string[] playerList = new string[gameSession.playerList.Count];
                        gameSession.playerList.CopyTo(playerList);
                        foreach (string player in playerList)
                        {
                            gameSession.RemovePlayer(player);
                            ILoginService login = ServiceProxy.Create <ILoginService>(new Uri(ServiceUri.AbsoluteUri.Replace("GameManagerActorService", "LoginService")));
                            await login.RemovePlayerAsync(Id.ToString());
                        }
                        InitializeGameAsync(gameSession.maxPlayers).Wait();
                    }
                    else
                    {
                        //Saves "gamesession" state
                        await this.StateManager.SetStateAsync("gamesession", gameSession);
                    }
                }
            }
            catch (Exception e)
            {
                response.info      = false;
                response.exception = e;
            }
            return(response);
        }
        /// <summary>
        /// Manages player attack
        /// </summary>
        /// <param name="i_player">Player name</param>
        public async Task <ServerResponseInfo <bool, Exception> > PlayerAttacksAsync(string i_player)
        {
            ServerResponseInfo <bool, Exception> response = new ServerResponseInfo <bool, Exception>();

            response.info = true;
            try
            {
                //Gets "gamesession" from StateManager
                GameSession gameSession = await this.StateManager.GetStateAsync <GameSession>("gamesession");

                //Manages player attack
                AttackResult result = gameSession.PlayerAttacks(i_player, PLAYER_ATTACK_RATE);
                //If player wasn't connected
                if (!result.success)
                {
                    response.info = false;
                }
                //Otherwise
                else
                {
                    List <string> message = new List <string>();
                    message.Add("BombHits");
                    message.Add(result.hitPoints.SerializeObject());
                    foreach (string player in gameSession.playerList)
                    {
                        SocketClient socket = new SocketClient();
                        socket.StartGameSessionClient(gameSession.GetPlayerAddress(player), message.SerializeObject() + "<EOF>");
                    }
                    //If there are players killed by the attack
                    if (result.killedPlayersDict.Count > 0)
                    {
                        //For each player
                        foreach (string killedPlayerId in result.killedPlayersDict.Keys)
                        {
                            message = new List <string>();
                            message.Add("PlayerKilled");
                            message.Add(killedPlayerId.SerializeObject());
                            message.Add(i_player.SerializeObject());
                            message.Add(result.killedPlayersDict[killedPlayerId].SerializeObject());
                            message.Add(DeathReason.PlayerHit.SerializeObject());
                            foreach (string player in gameSession.playerList)
                            {
                                SocketClient socket = new SocketClient();
                                socket.StartGameSessionClient(gameSession.GetPlayerAddress(player), message.SerializeObject() + "<EOF>");
                            }
                        }
                    }
                    //Saves "gamesession" state
                    await this.StateManager.SetStateAsync("gamesession", gameSession);

                    //If there's only one player alive
                    if (gameSession.AlivePlayers().Count == 1)
                    {
                        try
                        {
                            await this.UnregisterReminderAsync(GetReminder("TurretAim"));
                        }
                        catch (Exception e)
                        { }
                        try
                        {
                            await this.UnregisterReminderAsync(GetReminder("TurretShot"));
                        }
                        catch (Exception e)
                        { }
                        message = new List <string>();
                        message.Add("GameFinished");
                        message.Add(gameSession.AlivePlayers()[0].SerializeObject());
                        foreach (string player in gameSession.playerList)
                        {
                            SocketClient socket = new SocketClient();
                            socket.StartGameSessionClient(gameSession.GetPlayerAddress(player), message.SerializeObject() + "<EOF>");
                        }
                        string[] playerList = new string[gameSession.playerList.Count];
                        gameSession.playerList.CopyTo(playerList);
                        foreach (string player in playerList)
                        {
                            gameSession.RemovePlayer(player);
                            ILoginService login = ServiceProxy.Create <ILoginService>(new Uri(ServiceUri.AbsoluteUri.Replace("GameManagerActorService", "LoginService")));
                            await login.RemovePlayerAsync(Id.ToString());
                        }
                        InitializeGameAsync(gameSession.maxPlayers).Wait();
                    }
                }
            }
            catch (Exception e)
            {
                response.info      = false;
                response.exception = e;
            }
            return(response);
        }
        public async Task ReceiveReminderAsync(string reminderName, byte[] context, TimeSpan dueTime, TimeSpan period)
        {
            ActorEventSource.Current.Message("REMINDER RECIEVED");
            ActorEventSource.Current.Message("REMINDER NAME: " + reminderName);
            //Gets "gamesession" from Statemanager
            GameSession gameSession = await this.StateManager.GetStateAsync <GameSession>("gamesession");

            ActorEventSource.Current.Message("REMINDER: State gotten");
            //If LobbyCheck reminder
            if (reminderName.Equals("LobbyCheck"))
            {
                try
                {
                    ActorEventSource.Current.Message("REMINDER: LOBBY CHECK");
                    //Get players that are not connected
                    List <string> removedPlayers = gameSession.CheckPlayers();
                    //If there are players
                    if (removedPlayers.Count > 0)
                    {
                        //Disconnect each player
                        foreach (string removingPlayer in removedPlayers)
                        {
                            await PlayerDisconnectAsync(removingPlayer);
                        }
                    }
                    //If game is in Lobby state and lobby is full
                    if (gameSession.state.Equals(GameState.Lobby) && gameSession.isFull)
                    {
                        ActorEventSource.Current.Message("REMINDER: ALL PLAYERS");
                        //Unregister LobbyCheck reminder
                        await this.UnregisterReminderAsync(GetReminder("LobbyCheck"));

                        ActorEventSource.Current.Message("REMINDER: UNREGISTERED");
                        //Prepare game
                        gameSession.PrepareGame();
                        ActorEventSource.Current.Message("REMINDER: GAME PREPARED");
                        List <string> message = new List <string>();
                        ActorEventSource.Current.Message("REMINDER: STRINGLIST CREATED");
                        message.Add("GameStart");
                        ActorEventSource.Current.Message("REMINDER: GAMESTART ADDED");
                        message.Add(gameSession.getPlayerPositions.ToSerializable().SerializeObject());
                        ActorEventSource.Current.Message("REMINDER: PLAYER POSITIONS ADDED");
                        ActorEventSource.Current.Message("REMINDER: MESSAGE CREATED");
                        ActorEventSource.Current.Message("REMINDER: MESSAGE : " + message.SerializeObject());
                        ActorEventSource.Current.Message("REMINDER: MESSAGE LENGTH: " + message.SerializeObject().Length);
                        foreach (string player in gameSession.playerList)
                        {
                            SocketClient socket = new SocketClient();
                            socket.StartLobbyClient(gameSession.GetPlayerAddress(player), message.SerializeObject() + "<EOF>");
                        }
                        await this.RegisterReminderAsync("TurretAim", null, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(-1));
                    }
                    //otherwise
                    else
                    {
                        //Update lobby info
                        await UpdateLobbyInfoAsync();
                    }
                }
                catch (Exception e)
                {
                    ActorEventSource.Current.Message(e.ToString());
                }
            }
            if (reminderName.Equals("RemoveIfEmpty"))
            {
                ILoginService login = ServiceProxy.Create <ILoginService>(new Uri(ServiceUri.AbsoluteUri.Replace("GameManagerActorService", "LoginService")));
                login.DeleteGameAsync(Id.ToString(), ServiceUri.AbsoluteUri);
            }
            if (reminderName.Equals("TurretAim"))
            {
                if (context == null)
                {
                    int[]         aimPos  = gameSession.GetTurretAimPos(PLAYER_ATTACK_RATE);
                    List <string> message = new List <string>();
                    message.Add("TurretAiming");
                    message.Add(aimPos.SerializeObject());
                    foreach (string player in gameSession.playerList)
                    {
                        SocketClient socket = new SocketClient();
                        socket.StartGameSessionClient(gameSession.GetPlayerAddress(player), message.SerializeObject() + "<EOF>");
                    }
                    await this.RegisterReminderAsync("TurretAim", new byte[] { 1, (byte)aimPos[0], (byte)aimPos[1] }, TimeSpan.FromSeconds(1), TimeSpan.FromMilliseconds(-1));
                }
                else
                {
                    int   counter = context[0];
                    int[] aimPos  = new int[] { context[1], context[2] };
                    counter++;
                    List <string> message = new List <string>();
                    message.Add("TurretAiming");
                    message.Add(aimPos.SerializeObject());
                    foreach (string player in gameSession.playerList)
                    {
                        SocketClient socket = new SocketClient();
                        socket.StartGameSessionClient(gameSession.GetPlayerAddress(player), message.SerializeObject() + "<EOF>");
                    }
                    if (counter < 5)
                    {
                        await this.RegisterReminderAsync("TurretAim", new byte[] { (byte)counter, (byte)aimPos[0], (byte)aimPos[1] }, TimeSpan.FromSeconds(1), TimeSpan.FromMilliseconds(-1));
                    }
                    else
                    {
                        await this.RegisterReminderAsync("TurretShot", new byte[] { (byte)aimPos[0], (byte)aimPos[1] }, TimeSpan.FromSeconds(1), TimeSpan.FromMilliseconds(-1));
                    }
                }
            }
            if (reminderName.Equals("TurretShot"))
            {
                int[]         aimpos  = new int[] { context[0], context[1] };
                AttackResult  result  = gameSession.TurretAttacks(aimpos, PLAYER_ATTACK_RATE);
                List <string> message = new List <string>();
                message.Add("BombHits");
                message.Add(result.hitPoints.SerializeObject());
                foreach (string player in gameSession.playerList)
                {
                    SocketClient socket = new SocketClient();
                    socket.StartGameSessionClient(gameSession.GetPlayerAddress(player), message.SerializeObject() + "<EOF>");
                }
                //If there are players killed by the attack
                if (result.killedPlayersDict.Count > 0)
                {
                    //For each player
                    foreach (string killedPlayerId in result.killedPlayersDict.Keys)
                    {
                        message = new List <string>();
                        message.Add("PlayerDead");
                        message.Add(killedPlayerId.SerializeObject());
                        message.Add(result.killedPlayersDict[killedPlayerId].SerializeObject());
                        message.Add(DeathReason.Turret.SerializeObject());
                        foreach (string player in gameSession.playerList)
                        {
                            SocketClient socket = new SocketClient();
                            socket.StartGameSessionClient(gameSession.GetPlayerAddress(player), message.SerializeObject() + "<EOF>");
                        }
                    }
                }
                //If there's only one player alive
                if (gameSession.AlivePlayers().Count == 1)
                {
                    try
                    {
                        await this.UnregisterReminderAsync(GetReminder("TurretAim"));
                    }
                    catch (Exception e)
                    { }
                    try
                    {
                        await this.UnregisterReminderAsync(GetReminder("TurretShot"));
                    }
                    catch (Exception e)
                    { }
                    message = new List <string>();
                    message.Add("GameFinished");
                    message.Add(gameSession.AlivePlayers()[0].SerializeObject());
                    foreach (string player in gameSession.playerList)
                    {
                        SocketClient socket = new SocketClient();
                        socket.StartGameSessionClient(gameSession.GetPlayerAddress(player), message.SerializeObject() + "<EOF>");
                    }
                    string[] playerList = new string[gameSession.playerList.Count];
                    gameSession.playerList.CopyTo(playerList);
                    foreach (string player in playerList)
                    {
                        gameSession.RemovePlayer(player);
                        ILoginService login = ServiceProxy.Create <ILoginService>(new Uri(ServiceUri.AbsoluteUri.Replace("GameManagerActorService", "LoginService")));
                        await login.RemovePlayerAsync(Id.ToString());
                    }
                    InitializeGameAsync(gameSession.maxPlayers).Wait();
                }
                await this.RegisterReminderAsync("TurretAim", null, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(-1));
            }
            //Saves "gamesession" state
            await this.StateManager.SetStateAsync("gameSession", gameSession);
        }
Esempio n. 41
0
 /// <summary>
 /// Handles closed socket client connection.
 /// </summary>
 void IClientHandler.ConnectionClosed(SocketClient client)
 // SocketClient is actually ChatClient so it can be casted to our own type
 => onConnectionClosed(client as ChatClient);
 public SocketMessageEventArgs(SocketClient socket, string message) : base(socket)
 {
     this.Message = message;
 }
        private void GetGraphData()
        {
            //request
            //static part
            string xml_send = @"<?xml version=""1.0"" standalone=""yes""?><Requests xmlns:xsi=""='http://www.w3.org/2001/XMLSchema-instance'""  xmlns=""xmlns='http://tempuri.org/Requests.xsd\'""><Request><RequestName>";

            //dynamic part
            if (comboBox1.SelectedItem.ToString() == "RSSI" || comboBox1.SelectedItem.ToString() == "Position")
            {
                xml_send += "getLocHistoryLast</RequestName>";
            }
            else
            {
                xml_send += "getHistoryLast</RequestName>";
            }

            //return the nodeid with sensor as input
            try
            {
                string selectedNode = comboBox2.SelectedItem.ToString();

                if (selectedNode != null)
                {
                    string nodeid = getNodeID(selectedNode);;

                    xml_send += "<arg>" + nodeid + "</arg>";

                    string selectedReading = comboBox1.SelectedItem.ToString();

                    if (selectedReading != null)
                    {
                        xml_send += "<arg>" + selectedReading + "</arg><arg>10</arg></Request></Requests>";
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    return;
                }

                SocketClient socket_client = new SocketClient(Port, controllerIP.Text);
                string       xml_receive   = socket_client.Connect(xml_send, true);


                //proces the reply
                XmlDocument tempdoc = new XmlDocument();
                tempdoc.LoadXml(xml_receive);

                listView2.Items.Clear();
                XmlNodeList bookList = tempdoc.GetElementsByTagName("MeasurementValue");

                foreach (XmlNode node in bookList)
                {
                    string id_Measurement = node.InnerText.ToString();
                    listView2.Items.Add(id_Measurement);
                }

                CreateGraph(zg1, xml_receive);
                SetSize();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.HelpLink);
            }
        }
Esempio n. 44
0
 private static void ErrorThrown(SocketClient socketClient, Exception error)
 {
     WriteLine("The client has thrown an error: " + error.Message);
     WriteLine("Stacktrace: " + error.StackTrace);
 }
        //REMOVE GAME WHEN NO PLAYERS (REMINDER)???
        /// <summary>
        /// Disconnects player from GameSession
        /// </summary>
        /// <param name="i_player">Player name</param>
        /// <returns></returns>
        public async Task PlayerDisconnectAsync(string i_player)
        {
            //Gets "gamesession" from StateManagers
            GameSession gameSession = await this.StateManager.GetStateAsync <GameSession>("gamesession");

            //Removes player from game
            int[] posWhenDisconnected = gameSession.RemovePlayer(i_player);
            if (posWhenDisconnected != null)
            {
                List <string> message = new List <string>();
                message.Add("PlayerDead");
                message.Add(i_player.SerializeObject());
                message.Add(posWhenDisconnected.SerializeObject());
                message.Add(DeathReason.Disconnect.SerializeObject());
                foreach (string player in gameSession.playerList)
                {
                    SocketClient socket = new SocketClient();
                    socket.StartGameSessionClient(gameSession.GetPlayerAddress(player), message.SerializeObject() + "<EOF>");
                }
            }
            //If game is in Lobby state and there's no players
            if (gameSession.state.Equals(GameState.Lobby) && gameSession.connectedPlayerCount == 0)
            {
                //Gets LobbyCheck reminder and unregisters it
                IActorReminder reminder = GetReminder("LobbyCheck");
                await UnregisterReminderAsync(reminder);
            }
            ILoginService login = ServiceProxy.Create <ILoginService>(new Uri(ServiceUri.AbsoluteUri.Replace("GameManagerActorService", "LoginService")));
            await login.RemovePlayerAsync(Id.ToString());

            //Saves "gamesession" state
            await this.StateManager.SetStateAsync("gamesession", gameSession);

            //If there's only one player alive
            if (gameSession.AlivePlayers().Count == 1)
            {
                try
                {
                    await this.UnregisterReminderAsync(GetReminder("TurretAim"));
                }
                catch (Exception e)
                { }
                try
                {
                    await this.UnregisterReminderAsync(GetReminder("TurretShot"));
                }
                catch (Exception e)
                { }
                List <string> message = new List <string>();
                message.Add("GameFinished");
                message.Add(gameSession.AlivePlayers()[0].SerializeObject());
                foreach (string player in gameSession.playerList)
                {
                    SocketClient socket = new SocketClient();
                    socket.StartGameSessionClient(gameSession.GetPlayerAddress(player), message.SerializeObject() + "<EOF>");
                }
                string[] playerList = new string[gameSession.playerList.Count];
                gameSession.playerList.CopyTo(playerList);
                foreach (string player in playerList)
                {
                    gameSession.RemovePlayer(player);
                    login = ServiceProxy.Create <ILoginService>(new Uri(ServiceUri.AbsoluteUri.Replace("GameManagerActorService", "LoginService")));
                    await login.RemovePlayerAsync(Id.ToString());
                }
                InitializeGameAsync(gameSession.maxPlayers).Wait();
            }
            else if (gameSession.playerCount == 0)
            {
                await this.RegisterReminderAsync("RemoveIfEmpty", null, TimeSpan.FromSeconds(60), TimeSpan.FromMilliseconds(-1));
            }
        }
Esempio n. 46
0
        // Start is called before the first frame update
        void Start()
        {
            socketClient = new SocketClient();
            socketServer = GameObject.FindObjectOfType <SocketServer>();
            maker        = GameObject.FindObjectOfType <SpeechBubbleMaker>();
            uniwinc      = GameObject.FindObjectOfType <UniWindowController>();
            Node root    = new MenuNode();
            Node setting = new Node("せってい", 1);

            root.AddChild(setting);
            var setTransparent = new SwitchNode("背景透過中だよ", "背景透過してないよ", 1, uniwinc.isTransparent);

            setting.AddCallback(() =>
            {
                setTransparent.ON = uniwinc.isTransparent;
            });
            setTransparent.AddCallback(() =>
            {
                uniwinc.isTransparent = setTransparent.ON;
            });
            setting.AddChild(setTransparent);

            var setTopmost = new SwitchNode("最前面固定するよ", "最前面固定しないよ", 1, uniwinc.isTopmost);

            setting.AddCallback(() =>
            {
                setTopmost.ON = uniwinc.isTopmost;
            });
            setTopmost.AddCallback(() =>
            {
                uniwinc.isTopmost = setTopmost.ON;
            });
            setting.AddChild(setTopmost);

            var setTranslucent = new SwitchNode("半透明だよ", "半透明じゃないよ", 1, false);

            setTranslucent.AddCallback(() =>
            {
                canvasGroup.alpha = setTranslucent.ON ? 0.5f : 1.0f;
            });
            setting.AddChild(setTranslucent);

            var setRandspeak = new SwitchNode("話すよー", "黙ってるよ...", +1);

            setRandspeak.AddCallback(() =>
            {
                if (setRandspeak.ON)
                {
                    maker.StopSpeak();
                }
                else
                {
                    maker.StartSpeak();
                }
            });
            setting.AddChild(setRandspeak);
            Node remocon = new Node("リモコン", 1);
            // root.AddChild(remocon);
            Node right_off = new Node("明かりを消す?", 1);

            right_off.AddCallback(() =>
            {
                HttpCommunicator hc = new HttpCommunicator();
                var url             = "https://api.switch-bot.com/v1.0/devices/01-202101071744-43895891/commands";
                // hc.GetHttpAsync()
            });



            Node sensor = new Node("Sensor", 1);
            // root.AddChild(sensor);
            PythonExecutor pyexe = GameObject.FindObjectOfType <PythonExecutor>();

            socketServer.AddCommand("speak", mes =>
            {
                maker.GenerateFromThread(1, mes, 3, 1);
            });

            socketServer.AddCommand("long_speak", mes =>
            {
                maker.GenerateFromThread(1, mes, -1, 1);
            });

            socketServer.AddCommand("echo", mes =>
            {
                pyexe.SendCmd("nothing");
            });

            Node sensor_mes = new Node("Lauching...");

            sensor.AddChild(sensor_mes);
            pyexe.AddCommand("log", (mes) =>
            {
                Debug.Log("[python][log] " + mes);
            });

            sensor.AddCallback(() =>
            {
                sensor_mes.Text = "Lauching...";
                pyexe.ExecuteOnThread(); //実行
                Observable.Interval(TimeSpan.FromSeconds(1)).Subscribe(_ =>
                {
                    pyexe.p_WriteInputData("echo Message from C#");
                });
            });
            Node clock = new Node("Clock", 1);

            root.AddChild(clock);

            Node clock_display = new Node("--:--", 1);

            clock.AddChild(clock_display);

            IDisposable clock_update = null;

            clock.AddCallback(() =>
            {
                clock_update = Observable.Interval(TimeSpan.FromSeconds(0.1)).Subscribe(_ =>
                {
                    if (clock_display.speechBubble == null)
                    {
                        clock_update.Dispose();
                        return;
                    }
                    //clock_display.Text = DateTime.Now.ToShortTimeString();
                    clock_display.Text = DateTime.Now.ToLongTimeString();
                }).AddTo(this);
            });

            Node tool = new Node("Tool", 1);

            root.AddChild(tool);
            //Node bluetooth = new Node("Bluetooth\n ON");
            //tool.AddChild(bluetooth);
            Node pyexecutor_interface = new Node("pyexecutor");

            tool.AddChild(pyexecutor_interface);

            Node gui_start = new Node("GUIStart");

            pyexecutor_interface.AddChild(gui_start);

            pyexe.AddCommand("launched", (mes) =>
            {
                gui_start.Text = "GUI Launched";
            });

            gui_start.AddCallback(() =>
            {
                gui_start.Text = "GUI Started";
                pyexe.SendCmd("gui_start");
            });


            Node socketClientTest = new Node("SocketClient\nTest");

            socketClientTest.AddCallback(() =>
            {
                Task.Run(socketClient.ConnentionTest);
            });
            tool.AddChild(socketClientTest);

            Node shutdown = new Node("Shutdown");

            shutdown.AddCallback(() =>
            {
                #if UNITY_EDITOR
                UnityEditor.EditorApplication.isPlaying = false;
                #elif UNITY_STANDALONE
                UnityEngine.Application.Quit();
                #endif
            });
            tool.AddChild(shutdown);
            Node speaktest = new Node("speaktest");
            tool.AddChild(speaktest);
            Node title1 = new Node("精密計測工学2\n レポート");
            speaktest.AddChild(title1);
            // Node title2 = new Node("精密計測工学2");
            // speaktest.AddChild(title2);

            root.GenerateBubble(2);
        }
Esempio n. 47
0
 public ReceiveDataArges(SocketClient client, byte[] data)
 {
     Client = client;
     Data   = data;
 }
Esempio n. 48
0
 /// <summary> Called when a socket connection is accepted </summary>
 /// <param name="pSocket"> The SocketClient object the message came from </param>
 static public void AcceptHandler(SocketClient pSocket)
 {
     Console.WriteLine("Accept Handler");
     Console.WriteLine("IpAddress: " + pSocket.IpAddress);
     DataProccessor.clientsDict.Add(clientCount++, pSocket);
 }
Esempio n. 49
0
 private static void MessageFailed(SocketClient tcpClient, byte[] messageData, Exception exception)
 {
     WriteLine("The client has failed to send a message.");
     WriteLine("Error: " + exception);
 }
        /// <summary>
        /// Gets the statusdata off the selected node from the controller
        /// </summary>
        private void GetStatData()
        {
            //static part of the message
            string xml_send = @"<?xml version=""1.0"" standalone=""yes""?><Requests xmlns:xsi=""='http://www.w3.org/2001/XMLSchema-instance'""  xmlns=""xmlns='http://tempuri.org/Requests.xsd\'""><Request><RequestName>getStatus</RequestName>";

            //return the nodeid with sensor as input
            try
            {
                string selected = listBoxControl.SelectedItem.ToString();
                string nodeid   = getNodeID(selected);

                xml_send += "<arg>" + nodeid + "</arg></Request></Requests>";

                SocketClient socket_client = new SocketClient(Port, controllerIP.Text);
                // Receiving data
                string xml_receive = socket_client.Connect(xml_send, true);

                XmlDocument tempdoc = new XmlDocument();
                tempdoc.LoadXml(xml_receive);

                XmlNodeList bookList = tempdoc.GetElementsByTagName("Status");
                foreach (XmlNode node in bookList)
                {
                    XmlElement ID = (XmlElement)(node);
                    try
                    {
                        //assign the values of the textboxes


                        ActiveProperty = ID.GetElementsByTagName("active")[0].InnerText;
                        AnchorProperty = ID.GetElementsByTagName("AN")[0].InnerText;

                        textBoxControlX.Text   = ID.GetElementsByTagName("X")[0].InnerText;
                        textBoxControlY.Text   = ID.GetElementsByTagName("Y")[0].InnerText;
                        textBoxSampleRate.Text = ID.GetElementsByTagName("Samplerate")[0].InnerText;
                        textBoxLocRate.Text    = ID.GetElementsByTagName("LocRate")[0].InnerText;

                        //set the led bitmask
                        LedsProperty = ID.GetElementsByTagName("Leds")[0].InnerText;


                        PowerProperty     = ID.GetElementsByTagName("Power")[0].InnerText;
                        FrequencyProperty = ID.GetElementsByTagName("Frequency")[0].InnerText;

                        textBoxConn.Text = ID.GetElementsByTagName("Conn")[0].InnerText;
                    }
                    catch
                    {
                        Console.WriteLine("Some field is not available");
                    }

                    //backup these values in the changes struct
                    oldChanges.Active = ActiveProperty;
                    oldChanges.AN     = AnchorProperty;

                    oldChanges.X          = textBoxControlX.Text;
                    oldChanges.Y          = textBoxControlY.Text;
                    oldChanges.samplerate = textBoxSampleRate.Text;
                    oldChanges.locrate    = textBoxLocRate.Text;

                    oldChanges.power     = PowerProperty;
                    oldChanges.frequency = FrequencyProperty;
                    oldChanges.conn      = textBoxConn.Text;

                    oldChanges.leds = LedsProperty;
                }
            }
            catch
            {
                Console.WriteLine("Error in getStatData");
            }
        }
Esempio n. 51
0
 private static void ClientMessageSubmitted(SocketClient a, bool close)
 {
     WriteLine("The client has submitted a message to the server.");
 }
Esempio n. 52
0
 private static void Disconnected(SocketClient a, string ip, int port)
 {
     WriteLine("The client has disconnected from the server with ip " + a.Ip + "on port " + a.Port);
 }
Esempio n. 53
0
 private void ConnectFunc(SocketClient client)
 {
     client.Connect();
 }
Esempio n. 54
0
 private static void FileReceived(SocketClient a, string file)
 {
     WriteLine("The client has received a File/Folder and has saved this File/Folder at path :  " + file);
 }
Esempio n. 55
0
        private void DualModeConnect_AcceptAsync_Helper(IPAddress listenOn, IPAddress connectTo)
        {
            using (Socket serverSocket = new Socket(SocketType.Stream, ProtocolType.Tcp))
            {
                int port = serverSocket.BindToAnonymousPort(listenOn);
                serverSocket.Listen(1);

                SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                args.Completed += AsyncCompleted;
                ManualResetEvent waitHandle = new ManualResetEvent(false);
                args.UserToken   = waitHandle;
                args.SocketError = SocketError.SocketError;

                _log.WriteLine(args.GetHashCode() + " SocketAsyncEventArgs with manual event " + waitHandle.GetHashCode());
                if (!serverSocket.AcceptAsync(args))
                {
                    throw new SocketException((int)args.SocketError);
                }

                SocketClient client = new SocketClient(_log, serverSocket, connectTo, port);

                var waitHandles = new WaitHandle[2];
                waitHandles[0] = waitHandle;
                waitHandles[1] = client.WaitHandle;

                int completedHandle = WaitHandle.WaitAny(waitHandles, 5000);

                if (completedHandle == WaitHandle.WaitTimeout)
                {
                    throw new TimeoutException("Timed out while waiting for either of client and server connections...");
                }

                if (completedHandle == 1)   // Client finished
                {
                    if (client.Error != SocketError.Success)
                    {
                        // Client SocketException
                        throw new SocketException((int)client.Error);
                    }

                    if (!waitHandle.WaitOne(5000))  // Now wait for the server.
                    {
                        throw new TimeoutException("Timed out while waiting for the server accept...");
                    }
                }

                _log.WriteLine(args.SocketError.ToString());


                if (args.SocketError != SocketError.Success)
                {
                    throw new SocketException((int)args.SocketError);
                }

                Socket clientSocket = args.AcceptSocket;
                Assert.NotNull(clientSocket);
                Assert.True(clientSocket.Connected);
                Assert.Equal(AddressFamily.InterNetworkV6, clientSocket.AddressFamily);
                Assert.Equal(connectTo.MapToIPv6(), ((IPEndPoint)clientSocket.LocalEndPoint).Address);
                clientSocket.Dispose();
            }
        }
Esempio n. 56
0
 private static void ServerMessageReceived(SocketClient a, string msg)
 {
     WriteLine("Message received from the server: " + msg);
 }
Esempio n. 57
0
        private void RefreshGrid()
        {
            if (this.Tournament == null)
            {
                return;
            }

            if (this.Tournament.TournamentID == 0)
            {
                return;
            }

            this.panel1.Visible = false;
            dgvWinners.Visible  = false;

            if (this.Tournament.TournamentTypeIDE == TournamentTypeE.Scheveningen)
            {
                dgvSchTeamResult.AutoGenerateColumns = false;
                dgvTeamPoint.AutoGenerateColumns     = false;
                this.panel1.Visible = true;
            }

            ProgressForm frmProgress = ProgressForm.Show(this, "Loading Standings...");

            try
            {
                DataSet ds = SocketClient.GetTournamentResultById(this.Tournament.TournamentID);

                if (ds != null)
                {
                    if (ds.Tables.Count > 0)
                    {
                        table = ds.Tables[0];
                        RefreshGrid(table);
                        FillWinners(table);
                        if (ds.Tables.Count > 1)
                        {
                            FillSchTeamResult(ds.Tables[1]);
                        }
                        if (ds.Tables.Count > 2)
                        {
                            FillTeamUserPoint(ds.Tables[3]);
                        }
                    }
                    else
                    {
                        dgvResult.DataSource        = null;
                        dgvSchTeamResult.DataSource = null;
                        dgvTeamPoint.DataSource     = null;
                    }
                }
                else
                {
                    dgvResult.DataSource        = null;
                    dgvSchTeamResult.DataSource = null;
                    dgvTeamPoint.DataSource     = null;
                }

                foreach (DataGridViewRow row in dgvResult.Rows)
                {
                    if (row.Cells["CountryId"].Value.ToString() == "0")
                    {
                        Image item = Image.FromFile(Ap.FolderFlags + "244.png");
                        row.Cells["Flag"].Value = item;
                    }
                    else
                    {
                        Image item = Image.FromFile(Ap.FolderFlags + row.Cells["CountryId"].Value + ".png");
                        row.Cells["Flag"].Value = item;
                    }
                }
            }
            catch (Exception ex)
            {
                TestDebugger.Instance.WriteError(ex);
            }

            FormatGrid();
            frmProgress.Close();
        }
Esempio n. 58
0
 private static void ConnectedToServer(SocketClient a)
 {
     WriteLine("The client has connected to the server on ip " + a.Ip);
 }
        /// <summary>
        /// Fetches all the motes in the databases
        /// Has NO offline detection mechanism
        /// </summary>
        private void GetSensors()
        {
            string xml_send = @"<?xml version=""1.0"" standalone=""yes""?><Requests xmlns:xsi=""='http://www.w3.org/2001/XMLSchema-instance'""  xmlns=""xmlns='http://tempuri.org/Requests.xsd\'""><Request><RequestName>getAllTelosb</RequestName></Request></Requests>";

            SocketClient socket_client = new SocketClient(Port, controllerIP.Text);
            // Receiving data
            string xml_receive = socket_client.Connect(xml_send, true);

            #region alt. method: dataset
            ////Set up a memory-stream to store the xml
            //MemoryStream MemStream = new MemoryStream();
            ////Write the msg to the memory stream
            //StreamWriter SWriter = new StreamWriter(MemStream);
            //SWriter.WriteLine(xml_receive);
            //SWriter.Flush();
            //MemStream.Position = 0; //Reset the position so we start reading at the start
            ////store the xml data in a dataset
            //tempset.ReadXml(MemStream);

            //List<SensorNames> Sensorlijst = new List<SensorNames>();
            ////process the dataset
            //if (tempset.Tables.Count >= 1)
            //{   //Only send a reply if we actually got a correct Msg to send
            //    //(in other words, when the query actually succeeded)
            //    if ((tempset.Tables[0].Rows.Count <= 0))
            //    {   //We got a result back, but just nothing in it...
            //        //OutMsg = CreateReplyInt(0);
            //        ;
            //    }
            //    else
            //    {
            //        foreach (DataRow row in tempset.Tables[0].Rows) //Run through every sensor in the xml-message
            //        {
            //            Sensorlijst.Add(new SensorNames(row["nodeid"].ToString()));
            //        }
            //    }
            //}
            #endregion


            XmlDocument tempdoc = new XmlDocument();
            tempdoc.LoadXml(xml_receive);

            XmlNodeList bookList = tempdoc.GetElementsByTagName("Sensor");
            foreach (XmlNode node in bookList)
            {
                XmlElement ID = (XmlElement)(node);
                try
                {
                    string sensor = ID.GetElementsByTagName("sensor")[0].InnerText;
                    string idnode = ID.GetElementsByTagName("idnode")[0].InnerText;
                    Sensorlijst.Add(new SensorNames(sensor, idnode));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.TargetSite);
                }
            }

            Sensorlijst.ForEach(delegate(SensorNames SN)
            {
                comboBox2.Items.Add(SN.Sensorname);
                listBoxLoc.Items.Add(SN.Sensorname);
                listBoxControl.Items.Add(SN.Sensorname);
            });
        }
        /// <summary>
        /// Retreives the sensordata from the controller
        /// </summary>
        public void GetSensorData()
        {
            //static part of the message
            string xml_send = @"<?xml version=""1.0"" standalone=""yes""?><Requests xmlns:xsi=""='http://www.w3.org/2001/XMLSchema-instance'""  xmlns=""xmlns='http://tempuri.org/Requests.xsd\'""><Request><RequestName>getnodeInfo</RequestName>";

            //return the nodeid with sensor as input
            try
            {
                if (listBoxLoc.SelectedItem.ToString() != null)
                {
                    string nodeid = getNodeID(listBoxLoc.SelectedItem.ToString());

                    xml_send += "<arg>" + nodeid + "</arg></Request></Requests>";

                    SocketClient socket_client = new SocketClient(Port, controllerIP.Text);
                    // Receiving data
                    string xml_receive = socket_client.Connect(xml_send, true);


                    XmlDocument tempdoc = new XmlDocument();
                    tempdoc.LoadXml(xml_receive);

                    XmlNodeList bookList = tempdoc.GetElementsByTagName("SensorMeasurements");
                    foreach (XmlNode node in bookList)
                    {
                        XmlElement ID = (XmlElement)(node);
                        try
                        {
                            textBox1.Text = ID.GetElementsByTagName("Node")[0].InnerText;
                            textBox2.Text = ID.GetElementsByTagName("Sensortype")[0].InnerText;
                            textBox3.Text = ID.GetElementsByTagName("Temperature")[0].InnerText;
                            textBox4.Text = ID.GetElementsByTagName("Light")[0].InnerText;
                            textBox5.Text = ID.GetElementsByTagName("Humidity")[0].InnerText;
                            if (ID.GetElementsByTagName("Sensortype")[0].InnerText == "2")
                            {
                                textBox6.Text = ID.GetElementsByTagName("Power")[0].InnerText;
                            }
                            else
                            {
                                textBox6.Text = "N/A";
                            }
                            int index = ID.GetElementsByTagName("Time")[0].InnerText.IndexOf(' ');
                            textBoxSensUpdate.Text = ID.GetElementsByTagName("Time")[0].InnerText.Substring(index);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                }
                else
                {
                    return;
                }
            }
            catch
            {
                Console.WriteLine("Exception in GetSensorData");
                return;
            }
        }