Example #1
0
 private static void JoinServer(PacketHeader header, Connection connection, string message)
 {
     if (players.Count <= 8)
     {
         if (!players.ContainsKey(connection))
         {
             GameObject go = new GameObject();
             go.Tag = connection.ToString();
             go.AddComponent(new Enemy(go));
             go.AddComponent(new SpriteRenderer(go, "Player", 1));
             go.LoadContent(GameWorld.Instance.Content);
             players.Add(connection, go);
             GameWorld.gameObjects.Add(go);
             connection.SendObject <bool>("JoinedServerRespond", true);
         }
         else
         {
             connection.SendObject <bool>("JoinedServerRespond", false);
         }
     }
     else
     {
         connection.SendObject <bool>("JoinedServerRespond", false);
     }
 }
Example #2
0
 public void AcceptBlock(PacketHeader header, Connection connection, Block newBlock)
 {
     if (newBlock == null)
     {
         ConnectionHandled(); return;
     }
     if (!newBlock.isValid((newBlock.block_number / Environment.diffReducer) + Environment.initialDifficulty, _chain))
     {
         ConnectionHandled(); return;
     }
     if (!Enumerable.SequenceEqual(newBlock.prev_hash, _chain.getLastHash()))
     {
         //If the other chain is x blocks longer, request last 10 blocks;
         if (chainSize++ >= CoinFramework.Environment.TrustBlocks)
         {
             chainSize = 0;
             connection.SendObject <int>("SendChain", _chain.chain.Count - 10);
             ConnectionHandled();
             return;
         }
         else
         {
             return;
         }
     }
     if (newBlock.block_number != _chain.chain.Count + 1)
     {
         ConnectionHandled();
         return;
     }
     _chain.AddBlock(newBlock);
     connection.SendObject <int>("SendChain", _chain.chain.Count + 1);
 }
Example #3
0
        public void waitLoop()
        {
            Msg    msg = new Msg();
            string s;

            char[] data = new char[2];

            try
            {
                while ((s = Console.ReadLine()).Equals("!quit") == false)
                {
                    if (!gStart)
                    {
                        if (s.Length != 0)
                        {
                            msg.text = players[0] + ": " + s;
                            con.SendObject("Msg", msg);
                        }
                    }
                    else if (cmd == 0)
                    {
                        if (s.Length == 0)
                        {
                            data[0] = (char)0;
                            data[1] = (char)0;
                        }
                        else
                        {
                            data = getTrumpValues(s);
                            if (data[0] == 6)
                            {
                                continue;
                            }
                        }
                        sendCommand(data);
                        Console.WriteLine("Your answer has been sent...");
                        cmd = (char)255;
                    }
                    else if (cmd == 1)
                    {
                        if (s.Length == 0)
                        {
                            Console.WriteLine("You can't skip your turn, you have to chose a card.");
                            continue;
                        }
                        if ((data[0] = getCardToPlay(s)) == 32)
                        {
                            continue;
                        }
                        sendCommand(data);
                        Console.WriteLine("Your answer have been sent...");
                        cmd = (char)255;
                    }
                }
            }
            catch (IOException)
            {
                Console.WriteLine("failed to do smthg");
            }
        }
Example #4
0
        //Připojení klienta k serveru
        private static void ConnectUser(PacketHeader packetheader, Connection connection, string name)
        {
            IPEndPoint clientEndPoint = (IPEndPoint)connection.ConnectionInfo.RemoteEndPoint;

            //Uživatel se stejným jménem již existuje
            if (Clients.Any(x => x.Name == name))
            {
                string reason = string.Format($"Uživatelské jméno {name} je již zabrané!");

                ConnectResponse response = new ConnectResponse(ResponseType.Rejected, ServerName, reason);
                connection.SendObject("ConnectInfo", response);

                Console.WriteLine($"{name} se nepodařilo připojit k serveru z důvodu: {reason}");
            }
            //Přidání hráče
            else
            {
                Clients.Add(new Client(name, clientEndPoint.Address.ToString(), clientEndPoint.Port));

                ConnectResponse response = new ConnectResponse(ResponseType.Accepted, ServerName, Clients);
                connection.SendObject("ConnectInfo", response);

                Console.WriteLine($"({name}) se připojil k serveru (celkem  {Clients.Count} hráčů)");
            }

            //Aktualizace online klientů
            foreach (Client client in Clients)
            {
                NetworkComms.SendObject("UpdateListInfo", client.Ip, client.Port, Clients);
            }
        }
Example #5
0
        /// <summary>
        /// Generete new meme by a server and add to a database
        /// </summary>
        public async void GenerateMemeRequest(PacketHeader header, Connection connection, MemeDto message)
        {
            var  key         = message.Key;
            var  userId      = dummyAuthentication.LoggedUsers[key];
            var  memeContent = MemeBuilder.GenerateMeme(message);
            Meme meme        = new Meme()
            {
                Content     = imageToByteArray(memeContent),
                CreatedDate = DateTime.Now,
                UserId      = userId,
                Title       = message.ImageName
            };

            try
            {
                memeRepository.Add(meme);
                await memeRepository.SaveAsync();

                connection.SendObject(PacketTypes.CreateMeme.Response, "Meme added.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("\nError :( \nmessage:  " + ex.Message);
                connection.SendObject(PacketTypes.CreateMeme.Response, "Error ocured.");
            }
        }
Example #6
0
 public void AcceptSend(PacketHeader header, Connection connection, int msg)
 {
     if (!(_chain.chain.Count > msg))
     {
         connection.SendObject <Block>("AnswerChain", _chain.chain[msg]);
         return;
     }
     connection.SendObject <Block>("AnswerChain", null);
     connection.CloseConnection(false);
 }
        public void SendPlayer()
        {
            SetNetworkPlayer();
            float deltaMove = Vector2.Distance(new Vector2(previousNetPlayer.xPos, previousNetPlayer.yPos), new Vector2(netPlayer.xPos, netPlayer.yPos)); // probably want to change, expensive and inefficient calculation

            if (deltaMove > settings.MinDeltaMove)
            {
                serverConnection.SendObject("Player", netPlayer);
                previousNetPlayer = netPlayer.Clone();
            }
        }
Example #8
0
        private static void RunRPCFunctionHandler <T, I>(PacketHeader header, Connection connection, RemoteCallWrapper wrapper) where T : I
        {
            I          instance = default(I);
            MethodInfo funcRef  = typeof(I).GetMethod(wrapper.name);

            try
            {
                lock (locker)
                {
                    instance = (I)(RPCObjectsById[wrapper.instanceId].RPCObject);
                }
            }
            catch (Exception)
            {
                wrapper.result    = null;
                wrapper.Exception = "SERVER SIDE EXCEPTION\n\n" + "Invalid instanceID" + "\n\nEND SERVER SIDE EXCEPTION\n\n";
                connection.SendObject(header.PacketType, wrapper);
                return;
            }

            object[] args = null;

            if (wrapper.args == null)
            {
                args = new object[0];
            }
            else
            {
                args = (from arg in wrapper.args select arg.UntypedValue).ToArray();
            }

            try
            {
                wrapper.result = RPCArgumentBase.CreateDynamic(funcRef.Invoke(instance, args));
                wrapper.args   = (from arg in args select RPCArgumentBase.CreateDynamic(arg)).ToList();
            }
            catch (Exception e)
            {
                wrapper.result = null;

                if (e.InnerException != null)
                {
                    e = e.InnerException;
                }

                wrapper.Exception = "SERVER SIDE EXCEPTION\n\n" + e.ToString() + "\n\nEND SERVER SIDE EXCEPTION\n\n";
            }

            string returnPacketType = header.GetOption(PacketHeaderStringItems.RequestedReturnPacketType);

            connection.SendObject(returnPacketType, wrapper);
        }
Example #9
0
 public void RequestPeers(int count)
 {
     if (Status == PeerStatus.Connected)
     {
         var message = new RequestPeersMessage(count);
         if (ConnectionMode == ConnectionMode.Direct)
         {
             //проверка на дисконнект
             try
             {
                 Connection.SendObject(message.GetType().Name, message);
             }
             catch
             {
                 Status = PeerStatus.Disconnected;
                 Connect();
             }
         }
         else
         {
             tracker.SendMessageToPeer(message, this);
         }
         PeersRequestsCount++;
     }
     else
     {
         Connect();
     }
 }
Example #10
0
        public bool Login(Connection con, Login login)
        {
            //Username exists
            if (_users.Any(a => a.Name == login.Name))
            {
                return(false);
            }


            //ID exists
            if (GetUserByConnection(con) != null)
            {
                return(false);
            }

            var user = new User {
                Id = _currentId, Name = login.Name
            };

            user.SetConnection(con);
            _users.Add(user);

            login.Id = _currentId;
            con.SendObject("login", login);
            _currentId++;
            return(true);
        }
Example #11
0
        public void Disconnect()
        {
            allTrackers.Remove(this);

            OnTrackerDelete?.Invoke(this, new EventArgs());

            if (Status == TrackerStatus.Connected)
            {
                var message = new PeerDisconnectMessage(CommonHelpers.GetLocalEndPoint(CommonHelpers.PeerPort, true));
                try
                {
                    Connection.SendObject(message.GetType().Name, message);
                }
                catch { }
            }

            Task.Run(() =>
            {
                try
                {
                    Connection?.Dispose();
                    Connection = null;
                }
                catch { }
            });

            Status = TrackerStatus.Disconnected;

            CommonHelpers.LogTrackers(allTrackers);
        }
Example #12
0
        private static void NewInstanceRPCHandler <T, I>(PacketHeader header, Connection connection, string instanceName) where T : I, new()
        {
            lock (locker)
            {
                string instanceId = GetInstanceId(typeof(T).Name + instanceName + connection.ConnectionInfo.NetworkIdentifier.ToString());

                RPCRemoteObject wrapper = null;
                if (!RPCObjectsById.TryGetValue(instanceId, out wrapper))
                {
                    var instance = new T();
                    wrapper = new RPCRemoteObject(instance, typeof(I), RPCRemoteObject.RPCObjectType.Private, instanceId, timeoutByInterfaceType[typeof(I)]);
                    RPCObjectsById.Add(instanceId, wrapper);
                }

                wrapper.AddClientSubscription <T, I>(connection);

                if (!newConnectionByIdHandlers.ContainsKey(typeof(I)))
                {
                    var del = new NetworkComms.PacketHandlerCallBackDelegate <string>(RetrieveByIDRPCHandler <T, I>);

                    serverConnection.AppendIncomingPacketHandler <string>(typeof(I).Name + "-NEW-RPC-CONNECTION-BY-ID", del);
                    newConnectionByIdHandlers.Add(typeof(I), del);
                }

                string returnPacketType = header.GetOption(PacketHeaderStringItems.RequestedReturnPacketType);
                connection.SendObject(returnPacketType, instanceId);
            }
        }
Example #13
0
        // Methods
        #region FileSend
        void FileSend()
        {
            //This is our progress percent, between 0 and 1
            double progressPercentage = 0;

            //Initialise stream with 1MB
            byte[]           buffer         = new byte[1024 * 1024];
            ThreadSafeStream dataToSend     = new ThreadSafeStream(new System.IO.MemoryStream(buffer));
            long             totalBytesSent = 0;

            //We will send in chunks of 50KB
            int sendInChunksOfNBytes = 50 * 1024;

            //Get the connection to the target
            Connection connection = TCPConnection.GetConnection(new ConnectionInfo(this.serverIp, this.serverPort));

            do
            {
                //Determine the total number of bytes to send
                //We need to watch out for the end of the buffer when we send less than sendInChunksOfNBytes
                long bytesToSend = (buffer.Length - totalBytesSent > sendInChunksOfNBytes ? sendInChunksOfNBytes : buffer.Length - totalBytesSent);
                StreamSendWrapper streamWrapper = new StreamSendWrapper(dataToSend, totalBytesSent, bytesToSend);
                connection.SendObject("PartitionedSend", streamWrapper);
                totalBytesSent    += bytesToSend;
                progressPercentage = ((double)totalBytesSent / buffer.Length);
            }while (totalBytesSent < buffer.Length);
        }
Example #14
0
        public void GetMemesByUSerRequest(PacketHeader packetHeader, Connection connection, string incomingObject)
        {
            ConsoleMessage.ReqestReceived(packetHeader.PacketType);
            var memes = memeRepository.Include(x => x.User).Where(x => x.User.Name == incomingObject);

            connection.SendObject(PacketTypes.GetMemesByUser.Response, memes);
        }
Example #15
0
        private static void HandleGame(PacketHeader header, Connection connection, Message message)
        {
            System.Console.WriteLine("Data from Client #" + (_clients.IndexOf(connection) + 1) + " : " + message.Step);
            if (message.Step != Message.Steps.ERROR && game.CurStep != message.Step)
            {
                System.Console.WriteLine("Wrong step " + message.Step + " vs " + game.CurStep);
                Commands.SendError(connection, 103);
            }
            else if (response.ContainsKey(message.Step))
            {
                Player player = game.GetPlayer(connection);

                response[message.Step](game, connection, message);
            }
            else
            {
                Message resp = new Message
                {
                    Step = Message.Steps.ERROR,
                    Code = 100
                };
                System.Console.WriteLine("Invalid step : " + message.Step);
                connection.SendObject("CardGame", resp, customSendReceiveOptions);
            }
        }
Example #16
0
        /// <summary>
        /// Delegate for handling incoming packets.
        /// 处理接收到的数据包   事件是在多线程中回调的,不能实现确定回调的线程
        /// </summary>
        /// <param name="packetHeader">消息包头部</param>
        /// <param name="connection">底层的连接</param>
        /// <param name="incomingObject">接收到的消息</param>
        private static void PacketHandlerAction(PacketHeader packetHeader, Connection connection, string incomingObject)
        {
            //解析数据包处理,并发送

            #region 消息处理事件

            #endregion

            Random rand = new Random();
            Console.WriteLine("接收到:" + incomingObject + ",thread id =" + Thread.CurrentThread.ManagedThreadId);
            foreach (var existCon in GetExistingConnection())
            {
                Console.WriteLine(existCon.ConnectionInfo.RemoteEndPoint);
            }
            if (rand.Next(1, 4) == 1)
            {
                Console.WriteLine("发送");
                connection.SendObject(PacketType, "接收到:" + incomingObject);
                if (rand.Next(1, 3) == 1)
                {
                    Console.WriteLine("关闭");
                    NetworkComms.CloseAllConnections(ConnectionType.TCP);
                }
            }
        }
 private void ProcessCommandAsHost(PacketHeader packetHeader, Connection connection, Command cmd)
 {
     foreach (Connection hostConnection in NetworkComms.GetExistingConnection(ConnectionType.TCP))
     {
         connection.SendObject("Command", cmd);
     }
 }
Example #18
0
        /// <summary>
        /// Deletes a receipt record from the database along with all associated itemsale records.
        /// </summary>
        /// <param name="header">The packet header associated with the incoming message</param>
        /// <param name="connection">The connection used by the incoming message</param>
        /// <param name="stockID">ReceiptID to delete</param>
        private static void DeleteReceipt(PacketHeader header, Connection connection, int stockID)
        {
            int rows = 0;

            Console.WriteLine("\nDeleting: " + stockID + " for connection: " + connection.ToString() + "'.");
            DatabaseAccess dbconnect = new DatabaseAccess();

            if ((rows = dbconnect.DeleteItemSale(stockID)) != 0)
            {
                Console.WriteLine("Success deleting ItemSales.");
            }
            else
            {
                Console.WriteLine("Failed.");
            }

            if ((rows = dbconnect.DeleteReceipt(stockID)) != 0)
            {
                Console.WriteLine("Success deleting Receipt.");
            }
            else
            {
                Console.WriteLine("Failed.");
            }

            connection.SendObject("ReturnDeleteReceiptRecord", rows);
            Console.WriteLine("Done");
        }
Example #19
0
        // Connects a new user to server.
        private static void ConnectNewUser(PacketHeader header, Connection connection, string newUsername)
        {
            Console.WriteLine("New user joining: " + newUsername);
            // Create new user connection info
            ConnectionInfo newUser = new ConnectionInfo(newUsername, connection);

            // Create list of usernames from those connected. Let them know a new user has been added to the list
            List <string> connectedUserNames = new List <string>();

            // Adds user Id to allow client class to assign user id for sending packets
            connectedUserNames.Add(newUser.userId.ToString());

            foreach (KeyValuePair <int, ConnectionInfo> connectedUser in connections)
            {
                int    connectedUserId = connectedUser.Key;
                String username        = connectedUser.Value.username;
                connectedUserNames.Add(username);
                Connection connectionExistingUser = connectedUser.Value.connection;
                connectionExistingUser.SendObject("newUserAdded", newUsername);
            }

            // Add new user to existing user list and return list of all other users
            connections.Add(newUser.userId, newUser);
            connection.SendObject("ConnectionInfo", connectedUserNames);
        }
Example #20
0
        protected virtual void HandleIncomingHandShake(PacketHeader header, Connection connection, HandShake incomingMessage)
        {
            if (Clients.Count() <= 2)
            {
                //IPEndPoint clientIPEndPoint = (IPEndPoint) connection.ExistingLocalListenEndPoints(ConnectionType.TCP).Last();
                //NetworkComms.SendObject("Protocol", clientIPEndPoint.Address.ToString(), clientIPEndPoint.Port, "Connected");

                lock (lastPeerMessageDict)
                {
                    /*
                     * if (lastPeerMessageDict.ContainsKey(incomingMessage.SourceIdentifier))
                     * {
                     *  if (lastPeerMessageDict[incomingMessage.SourceIdentifier].MessageIndex < incomingMessage.MessageIndex)
                     *  {
                     *
                     *      lastPeerMessageDict[incomingMessage.SourceIdentifier] = incomingMessage;
                     *  }
                     * }
                     * else
                     * {
                     */
                    lastPeerMessageDict.Add(incomingMessage.SourceIdentifier, incomingMessage);
                    Clients.Add(new InternalPlayer(new Player(0, incomingMessage.Name), connection));
                    connection.SendObject("Message", "Your are Connected to Powker! Wait Another Player...");
                    //}
                }
            }
        }
Example #21
0
        private void OnConnectToPeerWithTrackerMessage(PacketHeader packetHeader, Connection connection, ConnectToPeerWithTrackerMessage incomingObject)
        {
            Peer peerToConnect = allPeers.FirstOrDefault(peer => peer.Address.Equals(incomingObject.RecieverAddress));

            if (peerToConnect != null)
            {
                if (!ConnectedPeers.Contains(peerToConnect))
                {
                    ConnectedPeers.Add(peerToConnect);
                }
                if (!peerToConnect.ConnectedPeers.Contains(this))
                {
                    peerToConnect.ConnectedPeers.Add(this);

                    try
                    {
                        peerToConnect.Connection.SendObject(incomingObject.GetType().Name, incomingObject);
                    }
                    catch
                    {
                        peerToConnect.OnError();
                    }
                }
            }
            //если трекер не нашел пир адресат то отправляем отправителю дисконнект адресата
            else
            {
                var message = new PeerDisconnectMessage(incomingObject.SenderAddress);

                Connection.SendObject(message.GetType().Name, message);
            }
        }
Example #22
0
            /// <summary>
            /// Send players list to a specific one
            /// </summary>
            private void SendClientsList(Connection connection, Message incomingMessage)
            {
                string clientsList = "[ ";

                lock (lastPeerMessageDict)
                {
                    string[] currentUsers = (from current in lastPeerMessageDict.Values orderby current.SourceName select current.SourceName).ToArray();
                    this.connectedClientsBox.Dispatcher.BeginInvoke(new Action <string[]>((users) =>
                    {
                        foreach (var username in users)
                        {
                            if (username != this.localName.Text && username != incomingMessage.SourceName)
                            {
                                clientsList += username + ", ";
                            }
                        }
                        if (clientsList == "[ ")
                        {
                            clientsList = "[empty]";
                        }
                        else
                        {
                            clientsList  = clientsList.Substring(0, clientsList.Length - 2);
                            clientsList += " ]";
                        }
                        Message clientsListMessage = new Message(NetworkComms.NetworkIdentifier, "Server", "CHAT", clientsList, messageSendIndex++);
                        connection.SendObject("Message", clientsListMessage);
                    }), new object[] { currentUsers });
                }
            }
Example #23
0
        private static void ForwardEvent(MidiEvent midiEvent)
        {
            if (MustFilterEvent(midiEvent))
            {
                return;
            }

            lastEvent = midiEvent;
            if ("Midi events to network".Equals(outputDeviceName, System.StringComparison.InvariantCulture))
            {
                try
                {
                    if (cnx != null)
                    {
                        cnx.SendObject("midiEvent", metobc.Convert(midiEvent));
                    }
                    else
                    {
                        MessageBox.Show("connection to receiver is not etablished!");
                    }
                }
                catch (CommsException ce)
                {
                    // TODO when connection is lost, this message always occur and cnx is not closed
                    Console.WriteLine("CommsException occurs : " + ce.Message);
                }
            }
            else
            {
                if (outputDevice != null)
                {
                    outputDevice.SendEvent(midiEvent);
                }
            }
        }
Example #24
0
 private void RequestPeerHash()
 {
     if (Status == PeerStatus.NoHashRecieved)
     {
         var message = new PeerHashMessage(VotingsUser.PublicKey, true);
         if (ConnectionMode == ConnectionMode.Direct)
         {
             //проверка на дисконнект
             try
             {
                 Connection.SendObject(message.GetType().Name, message);
             }
             catch
             {
                 Status = PeerStatus.Disconnected;
                 Connect();
             }
         }
         else
         {
             tracker.SendMessageToPeer(message, this);
         }
     }
     else if (Status == PeerStatus.Disconnected)
     {
         Connect();
     }
 }
Example #25
0
        /// <summary>
        /// Gives the card.
        /// </summary>
        /// <param name="card">Card.</param>
        public void GiveCard(Card card)
        {
            if (_deck == null)
            {
                throw new Exceptions.PlayerError("Player must have a deck associated.");
            }

            if (!_unitTest)
            {
                Console.WriteLine("Giving card to player " +
                                  ConnectionManager.Get(_connection).Pseudo + ": " +
                                  card.Type.ToString() + " | " + card.Color.ToString());
                PlayCard cardPck = new PlayCard
                {
                    CardValue = card.Type,
                    CardColor = card.Color
                };
                using (MemoryStream stream = new MemoryStream())
                {
                    Serializer.Serialize(stream, cardPck);
                    _connection.SendObject("PlayerGetGameCard", stream.ToArray());
                }
            }

            _cardsHand.Add(card);
            if (_cardsHand.Count > 8)
            {
                throw new ArgumentException("Added too many cards");
            }
        }
Example #26
0
        public void Run(Connection connect)
        {
            string input;
            var    quit = false;

            conn = connect;
            while (!quit)
            {
                input = System.Console.ReadLine().Trim();
                if (input.Length > 0)
                {
                    if (input == "/quit")
                    {
                        quit = true;
                    }
                    else if (input == "/usage")
                    {
                        System.Console.WriteLine("/join: join a new game\n/play [nb]: play the card by selecting its number\n" +
                                                 "/cards: show all your cards\n/bidding [nb] [color]: bid a number of points to reach and a color\n" +
                                                 "/coinche: bid your ennemies won't fit their bidding\n/surcoinche: bid you'll succeed\n/skip: pass your turn");
                    }
                    else if (input[0] == '/')
                    {
                        CommandsManager(input);
                    }
                    else
                    {
                        conn.SendObject("Chat", input, Client.customSendReceiveOptions);
                    }
                }
            }
        }
        private void sendMsg()
        {
            if (textBox1.Text.Length == 0)
            {
                return;
            }


            if (isHost == true)
            {
                messageHolder toSend = new messageHolder(host.name + ": " + textBox1.Text);
                ChatLog.Items.Add(host.name + ": " + textBox1.Text);
                List <ConnectionInfo> l = NetworkComms.AllConnectionInfo();

                foreach (ConnectionInfo i in l)
                {
                    TCPConnection.GetConnection(i).SendObject("Message", toSend);
                }
            }
            else
            {
                messageHolder toSend = new messageHolder(cinfo.name + ": " + textBox1.Text);
                ChatLog.Items.Add(cinfo.name + ": " + textBox1.Text);
                newTCPConn.SendObject("Message", toSend);
            }
            textBox1.Clear();
        }
        // client
        public ChatForm(Connection newTCPConn)
        {
            NetworkComms.AppendGlobalIncomingPacketHandler <messageHolder>("Message", addMessage);
            NetworkComms.AppendGlobalIncomingPacketHandler <clientInfo>("ClientInfo", c_addClient);

            clientList      = new ArrayList();
            this.newTCPConn = newTCPConn;

            InitializeComponent();
            isHost = false;
            cinfo  = new clientInfo("Anonymous");

            try
            {
                newTCPConn.SendObject("ClientInfo", cinfo);
            }
            catch (Exception e)
            {
                MessageBox.Show("ERR: " + e.Message);
                return;
            }

            String msg = "Connection successful.";

            ChatLog.Items.Add(msg);
            Users.Items.Add(cinfo.name);
            Rank.Items.Add("G");
        }
Example #29
0
        private void processHello(PacketHeader packetHeader, Connection connection, Hello msg)
        {
            Back b = new Back();

            if (!room.isPlayerRegistered(msg.text))
            {
                b.text = "[server] Welcome, you are currently in the waiting room, waiting for a game to begin.";
                connection.SendObject <Back>("Back", b);
                room.AddPlayer(connection, msg.text);
            }
            else
            {
                b.text = "[!server] Seems like an other player is already using this name. Try an other one";
                connection.SendObject <Back>("Back", b);
            }
        }
Example #30
0
        public void LoginRequest(PacketHeader packetHeader, Connection connection, LoginDto incomingObject)
        {
            Console.WriteLine("\nLogin request received..");
            //response
            var loginResponseDto = new LoginResponseDto();

            // getting requested user
            User user = userRepository
                        .GetAllByCondition(x => x.Name == incomingObject.Login)
                        .FirstOrDefault();

            if (user == null)
            {
                UserNotFoundMethod(connection, loginResponseDto);
            }

            if (!String.Equals(user.Password, incomingObject.Password))
            {
                WrongPasswordMethod(connection, loginResponseDto);
            }

            Console.WriteLine("Login request successful:");
            Console.WriteLine("User: '******' logged to a server.", incomingObject.Login);

            loginResponseDto.Key     = dummyAuthentication.AddUser(user.UserId);
            loginResponseDto.Message = "Logging successful.";

            connection.SendObject(PacketTypes.Login.Response, loginResponseDto);
        }
        /// <summary>
        /// Handle the incoming peer discovery packet
        /// </summary>
        /// <param name="header"></param>
        /// <param name="connection"></param>
        /// <param name="data"></param>
        private static void PeerDiscoveryHandler(PacketHeader header, Connection connection, byte[] data)
        {            
            DiscoveryMethod discoveryMethod = DiscoveryMethod.UDPBroadcast;

#if !NETFX_CORE && !WINDOWS_PHONE
            if (connection.ConnectionInfo.ConnectionType == ConnectionType.TCP)
                discoveryMethod = DiscoveryMethod.TCPPortScan;
#endif
#if NET35 || NET4
            else if (connection.ConnectionInfo.ConnectionType == ConnectionType.Bluetooth)
                discoveryMethod = DiscoveryMethod.BluetoothSDP;
#endif

            //Ignore discovery packets that came from this peer
            if (!Connection.ExistingLocalListenEndPoints(connection.ConnectionInfo.ConnectionType).Contains(connection.ConnectionInfo.RemoteEndPoint))
            {
                //If the only thing that was sent was an empty byte array this is a peer discovery request. 
                if (data.Length == 0 && IsDiscoverable(discoveryMethod))
                {
                    //Send back our listener info 
                    byte[] responseData = SerializeLocalListenerList();
                    connection.SendObject(discoveryPacketType, responseData);
                }
                else if (data.Length > 0)
                {
                    //This is a peer discovery reply, we may need to add this to the tracking dictionary
                    ShortGuid peerIdentifier;

                    //If this is the case then we have found listeners on a peer and we need to add them to our known peers
                    List<PeerListenerEndPoint> remoteListeners = DeserializeRemoteListenerList(data, out peerIdentifier);

                    Dictionary<ConnectionType, List<EndPoint>> discoveredPeerListeners = new Dictionary<ConnectionType, List<EndPoint>>();
                    foreach (PeerListenerEndPoint peer in remoteListeners)
                    {
                        if (discoveredPeerListeners.ContainsKey(peer.ConnectionType))
                            discoveredPeerListeners[peer.ConnectionType].Add(peer.EndPoint);
                        else
                            discoveredPeerListeners.Add(peer.ConnectionType, new List<EndPoint>() { peer.EndPoint });
                    }

                    bool newlyDiscoveredPeerEndPoint = false;
                    lock (_syncRoot)
                    {
                        if (!_discoveredPeers.ContainsKey(peerIdentifier))
                            _discoveredPeers.Add(peerIdentifier, new Dictionary<ConnectionType, Dictionary<EndPoint, DateTime>>());

                        //If no remote listeners were returned we can only used the remoteEndPoint used to send this reply
                        if (remoteListeners.Count == 0)
                        {
                            if (!_discoveredPeers[peerIdentifier].ContainsKey(connection.ConnectionInfo.ConnectionType))
                                _discoveredPeers[peerIdentifier].Add(connection.ConnectionInfo.ConnectionType, new Dictionary<EndPoint, DateTime>());

                            if (!_discoveredPeers[peerIdentifier][connection.ConnectionInfo.ConnectionType].ContainsKey(connection.ConnectionInfo.RemoteEndPoint))
                            {
                                newlyDiscoveredPeerEndPoint = true;
                                _discoveredPeers[peerIdentifier][connection.ConnectionInfo.ConnectionType].Add(connection.ConnectionInfo.RemoteEndPoint, DateTime.Now);
                            }
                        }
                        else
                        {
                            foreach (PeerListenerEndPoint peerEndPoint in remoteListeners)
                            {
                                if (!_discoveredPeers[peerIdentifier].ContainsKey(peerEndPoint.ConnectionType))
                                {
                                    newlyDiscoveredPeerEndPoint = true;
                                    _discoveredPeers[peerIdentifier].Add(peerEndPoint.ConnectionType, new Dictionary<EndPoint, DateTime>() { { peerEndPoint.EndPoint, DateTime.Now } });
                                }
                                else if (!_discoveredPeers[peerIdentifier][peerEndPoint.ConnectionType].ContainsKey(peerEndPoint.EndPoint))
                                {
                                    newlyDiscoveredPeerEndPoint = true;
                                    _discoveredPeers[peerIdentifier][peerEndPoint.ConnectionType].Add(peerEndPoint.EndPoint, DateTime.Now);
                                }
                            }
                        }
                    }

                    //Trigger the discovery event if it has been set AND this is the first time a new peer end point was discovered
                    //If a peer is discoverable on multiple adaptors which we have access too we may receive numerous (duplicate)
                    //discovery reports. We are only interested in triggering on the first one, not subsequent identical copies.
                    //This ensures the synchronous and asynchronous methods execute in a similar fashion
                    if (OnPeerDiscovered != null && newlyDiscoveredPeerEndPoint)
                        OnPeerDiscovered(peerIdentifier, discoveredPeerListeners);
                }
            }
        }
Example #32
0
        /// <summary>
        /// UDP - Received when a peer request a chunk
        /// </summary>
        /// <param name="packetHeader"></param>
        /// <param name="connection"></param>
        /// <param name="incomingRequest"></param>
        private static void IncomingChunkInterestRequest(PacketHeader packetHeader, Connection connection, ChunkAvailabilityRequest incomingRequest)
        {
            try
            {
                //A peer has requested a specific chunk of data, we will only provide it if we are not already providing it to someone else
                DateTime startTime = DateTime.Now;

                //Console.WriteLine("... ({0}) received request for chunk {1} from {2}.", DateTime.Now.ToString("HH:mm:ss.fff"), incomingRequest.ChunkIndex, sourceConnectionId);
                if (DFS.loggingEnabled) DFS._DFSLogger.Trace("IncomingChunkInterestRequest from " + connection + " for " + incomingRequest.ItemCheckSum + ", chunkIndex " + incomingRequest.ChunkIndex + ".");

                DistributedItem selectedItem = null;
                lock (globalDFSLocker)
                    if (swarmedItemsDict.ContainsKey(incomingRequest.ItemCheckSum))
                        selectedItem = swarmedItemsDict[incomingRequest.ItemCheckSum];

                if (selectedItem == null || (selectedItem != null && selectedItem.ItemClosed))
                {
                    //First reply and say the peer can't have the requested data. This prevents a request timing out
                    connection.SendObject("DFS_ChunkAvailabilityInterestReplyInfo", new ChunkAvailabilityReply(NetworkComms.NetworkIdentifier, incomingRequest.ItemCheckSum, incomingRequest.ChunkIndex, ChunkReplyState.ItemOrChunkNotAvailable), nullCompressionSRO);

                    //Inform peer that we don't actually have the requested item
                    UDPConnection.SendObject("DFS_ItemRemovalUpdate", new ItemRemovalUpdate(NetworkComms.NetworkIdentifier, incomingRequest.ItemCheckSum, false), (IPEndPoint)connection.ConnectionInfo.RemoteEndPoint, nullCompressionSRO);

                    if (DFS.loggingEnabled) DFS._DFSLogger.Trace(" ... item not available locally, sent DFS_ItemRemovalUpdate.");
                }
                else
                {
                    //A little request validation
                    if (incomingRequest.ChunkIndex > selectedItem.Data.TotalNumChunks)
                        throw new InvalidDataException("The incoming request wanted chunk #" + incomingRequest.ChunkIndex +
                            " when the selected item only has " + selectedItem.Data.TotalNumChunks + "chunks.");

                    if (!selectedItem.ChunkAvailableLocally(incomingRequest.ChunkIndex))
                    {
                        //First reply and say the peer can't have the requested data. This prevents a request timing out
                        connection.SendObject("DFS_ChunkAvailabilityInterestReplyInfo", new ChunkAvailabilityReply(NetworkComms.NetworkIdentifier, incomingRequest.ItemCheckSum, incomingRequest.ChunkIndex, ChunkReplyState.ItemOrChunkNotAvailable), nullCompressionSRO);

                        //If the peer thinks we have a chunk we don't we send them an update so that they are corrected
                        UDPConnection.SendObject("DFS_PeerChunkAvailabilityUpdate", new PeerChunkAvailabilityUpdate(NetworkComms.NetworkIdentifier, incomingRequest.ItemCheckSum, selectedItem.SwarmChunkAvailability.PeerChunkAvailability(NetworkComms.NetworkIdentifier)), (IPEndPoint)connection.ConnectionInfo.RemoteEndPoint, nullCompressionSRO);

                        if (DFS.loggingEnabled) DFS._DFSLogger.Trace(" ... requested chunk not available, sent DFS_PeerChunkAvailabilityUpdate.");
                    }
                    else
                    {
                        //If we are a super peer we always have to respond to the request
                        if (HostInfo.IP.AverageNetworkLoadOutgoing(10) > DFS.PeerBusyNetworkLoadThreshold && !selectedItem.SwarmChunkAvailability.PeerIsSuperPeer(NetworkComms.NetworkIdentifier))
                        {
                            //We can return a busy reply if we are currently experiencing high demand
                            connection.SendObject("DFS_ChunkAvailabilityInterestReplyInfo", new ChunkAvailabilityReply(NetworkComms.NetworkIdentifier, incomingRequest.ItemCheckSum, incomingRequest.ChunkIndex, ChunkReplyState.PeerBusy), nullCompressionSRO);

                            if (DFS.loggingEnabled) DFS._DFSLogger.Trace(" ... peer busy, sent busy response.");
                        }
                        else
                        {
                            StreamTools.StreamSendWrapper chunkData = selectedItem.GetChunkDataStream(incomingRequest.ChunkIndex);

                            if (DFS.loggingEnabled) DFS._DFSLogger.Trace("Pushing chunkData to " + connection + " for item:" + incomingRequest.ItemCheckSum + ", chunkIndex:" + incomingRequest.ChunkIndex + ".");

                            //We identify the data using the itemchecksum, the requested chunk index, and to unique identify this request from possible duplicates
                            //we append the requesting peer request index.
                            string packetIdentifier = selectedItem.Data.CompleteDataCheckSum + "-" + incomingRequest.ChunkIndex + "-" + incomingRequest.RequestNumIndex;

                            //This is received via UDP but we want to reply using TCP to ensure delivery of the data
                            var clientTCPConnection = TCPConnection.GetConnection(new ConnectionInfo(connection.ConnectionInfo.RemoteEndPoint));

                            //Send using a custom packet so that we can add the packet identifier
                            using (Packet sendPacket = new Packet("DFS_ChunkAvailabilityInterestReplyData", chunkData, nullCompressionSRO))
                            {
                                sendPacket.PacketHeader.SetOption(PacketHeaderStringItems.PacketIdentifier, packetIdentifier);
                                clientTCPConnection.SendPacket<StreamTools.StreamSendWrapper>(sendPacket);
                            }

                            if (DFS.loggingEnabled) DFS._DFSLogger.Trace("Pushing chunkInfo to " + connection + " for item:" + incomingRequest.ItemCheckSum + ", chunkIndex:" + incomingRequest.ChunkIndex + ".");

                            clientTCPConnection.SendObject("DFS_ChunkAvailabilityInterestReplyInfo", new ChunkAvailabilityReply(NetworkComms.NetworkIdentifier, incomingRequest.ItemCheckSum, incomingRequest.ChunkIndex, packetIdentifier), nullCompressionSRO);

                            lock (TotalNumReturnedChunkRequestsLocker) TotalNumReturnedChunkRequests++;

                            if (DFS.loggingEnabled) DFS._DFSLogger.Trace(" ... IncomingChunkInterestRequest completed with data in " + (DateTime.Now - startTime).TotalSeconds.ToString("0.0") + " seconds.");
                        }
                    }
                }
            }
            catch (ObjectDisposedException)
            {
                //This happens if we dispose the DFS item during this method execution
                if (loggingEnabled) Logger.Warn("Prevented ObjectDisposedException in IncomingChunkInterestRequest");
            }
            catch (ConnectionSetupException)
            {
                //Ignore, the peer is offline
            }
            catch (CommunicationException)
            {
                //Ignore, connection is probably closed
            }
            catch (ConnectionSendTimeoutException)
            {
                //Ignore, the peer is suspended
            }
            catch (DuplicateConnectionException)
            {
                //Ignore, two peers tried to connect simultaneously 
            }
            catch (ConnectionShutdownException)
            {
                //Ignore, the peer disconnected
            }
            catch (CommsException e)
            {
                //Something f****d happened.
                //Console.WriteLine("IncomingChunkInterestRequestError. Error logged.");
                LogTools.LogException(e, "CommsError_IncomingChunkInterestRequest");
            }
            catch (Exception e)
            {
                LogTools.LogException(e, "Error_IncomingChunkInterestRequest");
            }
        }
Example #33
0
        /// <summary>
        /// TCP - A remote peer is trying to link DFS items
        /// </summary>
        /// <param name="packetHeader"></param>
        /// <param name="connection"></param>
        /// <param name="linkRequestData"></param>
        private static void IncomingRemoteItemLinkRequest(PacketHeader packetHeader, Connection connection, DFSLinkRequest linkRequestData)
        {
            try
            {
                var localItemKeys = AllLocalDFSItemsWithBuildTime();

                //We only check for potential links if the remote end has provided us with some items to link
                if (linkRequestData.AvailableItems.Count > 0)
                {
                    //Get the item matches using linq. Could also use localItemKeys.Intersect<long>(linkRequestData.AvailableItemCheckSums);
                    DistributedItem[] itemsToLink = null;

                    lock (globalDFSLocker)
                        itemsToLink= (from current in localItemKeys.Keys
                                          join remote in linkRequestData.AvailableItems.Keys on current equals remote
                                      where swarmedItemsDict.ContainsKey(current)
                                      select swarmedItemsDict[current]).ToArray();

                        for (int i = 0; i < itemsToLink.Length; i++)
                            itemsToLink[i].SwarmChunkAvailability.AddOrUpdateCachedPeerChunkFlags(connection.ConnectionInfo, new ChunkFlags(itemsToLink[i].Data.TotalNumChunks), true);
                }

                //If this link request is from the original requester then we reply with our own items list
                if (!linkRequestData.LinkRequestReply)
                {
                    //If a specific return packet type has been requested we use that
                    if (packetHeader.RequestedReturnPacketType != null)
                        connection.SendObject(packetHeader.RequestedReturnPacketType, new DFSLinkRequest(localItemKeys, true), nullCompressionSRO);
                    else
                        connection.SendObject("DFS_ItemLinkRequest", new DFSLinkRequest(localItemKeys, true), nullCompressionSRO);
                }
            }
            catch (CommsException e)
            {
                LogTools.LogException(e, "CommsError_IncomingRemoteItemLinkRequest");
            }
            catch (Exception e)
            {
                LogTools.LogException(e, "Error_IncomingRemoteItemLinkRequest");
            }
        }
Example #34
0
        /// <summary>
        /// Introduces a new item into the swarm and sends a build command to the originating requester
        /// </summary>
        /// <param name="peerConnection">The peer which requested the DFS item</param>
        /// <param name="itemToDistribute">The item to be distributed</param>
        /// <param name="completedPacketType">The packet type to use once the item has been fully assembled</param>
        public static void PushItemToPeer(Connection peerConnection, DistributedItem itemToDistribute, string completedPacketType)
        {
            try
            {
                if (peerConnection.ConnectionInfo.ConnectionType != ConnectionType.TCP)
                    throw new Exception("Only able to push DFS item when the request is made via TCP.");


                if (itemToDistribute.ItemClosed)
                    throw new ArgumentException("Unable to push a closed item.");

                ItemAssemblyConfig assemblyConfig;
                lock (globalDFSLocker)
                {
                    //First double check to see if it's already in the swarm
                    if (!ItemAlreadyInLocalCache(itemToDistribute))
                        swarmedItemsDict.Add(itemToDistribute.Data.CompleteDataCheckSum, itemToDistribute);
                    else
                        itemToDistribute = swarmedItemsDict[itemToDistribute.Data.CompleteDataCheckSum];
                }

                itemToDistribute.IncrementPushCount();

                //We add the requester to the item swarm at this point
                itemToDistribute.SwarmChunkAvailability.AddOrUpdateCachedPeerChunkFlags(peerConnection.ConnectionInfo, new ChunkFlags(0));

                //There is a possibility when we create this assembly config that the peer has been removed again
                //We handle this on the peer end
                assemblyConfig = new ItemAssemblyConfig(itemToDistribute, completedPacketType);

                //Send the config information to the client that wanted the file
                peerConnection.SendObject("DFS_IncomingLocalItemBuild", assemblyConfig, nullCompressionSRO);

                if (DFS.loggingEnabled) DFS._DFSLogger.Debug("Pushed DFS item " + itemToDistribute.Data.CompleteDataCheckSum + " to peer " + peerConnection + ".");
            }
            catch (CommsException)
            {
                //LogTools.LogException(ex, "CommsError_AddItemToSwarm");
            }
            catch (Exception ex)
            {
                LogTools.LogException(ex, "Error_AddItemToSwarm");
            }

            //try { GC.Collect(); }
            //catch (Exception) { }
        }