コード例 #1
0
            public async Task <ClientEntry> GetNexClient()
            {
                if (_disposedValue)
                {
                    throw new ObjectDisposedException(nameof(ClientPool));
                }

                ClientEntry entry = null;

                if (_enablePool)
                {
                    while (entry == null && !TryDequeue(out entry))
                    {
                        ////Interlocked.Increment(ref StaticLog.CreatedClients);
                        entry = new ClientEntry(new TcpClient(_endpoint.AddressFamily)
                        {
                            LingerState = new LingerOption(true, 0)
                        });
                        await entry.Client.ConnectAsync(_endpoint.Address, _endpoint.Port).ConfigureAwait(false);
                    }
                }
                else
                {
                    ////Interlocked.Increment(ref StaticLog.CreatedClients);
                    entry = new ClientEntry(new TcpClient(_endpoint.AddressFamily));
                    await entry.Client.ConnectAsync(_endpoint.Address, _endpoint.Port).ConfigureAwait(false);
                }

                return(entry);
            }
コード例 #2
0
 public void AttachClient(string name)
 {
     var client = OperationContext.Current.GetCallbackChannel<IChatClient>();
     var clientEntry = new ClientEntry {Name = name, Client = client};
     _clients.Add(clientEntry);
     NotifyUsersChanged();
 }
コード例 #3
0
            public void Enqueue(ClientEntry entry)
            {
                if (_disposedValue)
                {
                    throw new ObjectDisposedException(nameof(ClientPool));
                }
                if (entry == null)
                {
                    throw new ArgumentNullException(nameof(entry));
                }
                if (!entry.Client.Client.RemoteEndPoint.Equals(_endpoint))
                {
                    throw new ArgumentException("Invalid endpoint.");
                }

                // TickCount swap will be fine here as the entry just gets disposed and we'll create a new one starting at 0+ again, totall fine...
                if (_enablePool && entry.Client.Connected && entry.StartMillis + entry.MaxLiveTime >= (Environment.TickCount & int.MaxValue))
                {
                    _clients.Enqueue(entry);
                }
                else
                {
                    // dispose the client and don't keep a reference
                    entry.DisposeClient();
                }
            }
コード例 #4
0
        public async Task Put(int id, [FromBody] ClientEntry value)
        {
            var entry = await _db.Entries.FindAsync(id);

            entry = value;
            await _db.SaveChangesAsync();
        }
コード例 #5
0
            public async Task <ClientEntry> GetNextClient()
            {
                if (disposedValue)
                {
                    throw new ObjectDisposedException(nameof(ClientPool));
                }

                ClientEntry entry = null;

                if (_enablePool)
                {
                    while (entry == null && !TryDequeue(out entry))
                    {
                        entry = new ClientEntry(new TcpClient(_endpoint.AddressFamily)
                        {
                            LingerState = new LingerOption(true, 0)
                        }, _endpoint);
                        await entry.Client.ConnectAsync(_endpoint.Address, _endpoint.Port).ConfigureAwait(false);
                    }
                }
                else
                {
                    entry = new ClientEntry(new TcpClient(_endpoint.AddressFamily), _endpoint);
                    await entry.Client.ConnectAsync(_endpoint.Address, _endpoint.Port).ConfigureAwait(false);
                }

                return(entry);
            }
        public ActionResult DeleteConfirmed(int id)
        {
            ClientEntry clientEntry = db.ClientEntry.Find(id);

            db.ClientEntry.Remove(clientEntry);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
コード例 #7
0
        public async Task <string> Post([FromBody] ClientEntry value)
        {
            await _db.Entries.AddAsync(value);

            await _db.SaveChangesAsync();

            return(value.ClientName + " - " + value.ClientId);
        }
        public ActionResult Simulation([Bind(Include = "Id,Date,IsGoesInside,IdEntryGate,IdWristband")] ClientEntry clientEntry)
        {
            bool activeTicket = false;

            var entryGate = db.EntryGate.Find(clientEntry.IdEntryGate);


            var clientTickets = db.ClientTicket.Select(n => n).
                                Where(n => n.IdWristband == clientEntry.IdWristband).
                                Where(n => n.TicketInPriceList.Attraction.Id == entryGate.IdAttraction);

            foreach (ClientTicket ticket in clientTickets)
            {
                if (ticket.ExpirationDate < DateTime.Now)
                {
                    ticket.IsActive        = false;
                    db.Entry(ticket).State = EntityState.Modified;
                    continue;
                }
                else if (ticket.EntriesLeft != null)
                {
                    if (ticket.EntriesLeft <= 0)
                    {
                        ticket.IsActive        = false;
                        db.Entry(ticket).State = EntityState.Modified;
                        continue;
                    }

                    ticket.EntriesLeft    -= 1;
                    db.Entry(ticket).State = EntityState.Modified;
                }
                activeTicket = true;
                break;
            }

            clientEntry.Date = DateTime.Now;


            if (ModelState.IsValid && activeTicket)
            {
                db.ClientEntry.Add(clientEntry);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            var entryGates = db.EntryGate.Select(n => new
            {
                Id          = n.Id,
                Description = n.Attraction.Name + " " + n.Id,
                IsActive    = n.IsActive
            });

            ViewBag.NoTicketsForAttraction = true;

            ViewBag.IdEntryGate = new SelectList(entryGates.Where(n => n.IsActive == true), "Id", "Description", clientEntry.IdEntryGate);
            ViewBag.IdWristband = new SelectList(db.Wristband, "Id", "Id", clientEntry.IdWristband);
            return(View(clientEntry));
        }
コード例 #9
0
ファイル: ServerCore.cs プロジェクト: LootKeeper/SocketChat
        private void ClientAcceptHandler(object sender, TcpClient client)
        {
            ClientEntry entry = new ClientEntry(client);

            entry.OnMessageRecieve += MessageRecieved;
            if (_anons.TryAdd(entry.Ip, entry))
            {
                Console.WriteLine($"{client.Client.LocalEndPoint.ToString()} connected");
            }
        }
コード例 #10
0
    public void Init(ClientEntry clientEntry)
    {
        this.clientEntry = clientEntry;

        UIManager.Instance.Init();

        LogicModules.Instance.Initialize();

        inited = true;

        GlobalDispatcher.Instance.dispatchEvent(EventName.ShowStartView);
    }
 public ActionResult Edit([Bind(Include = "Id,Date,IsGoesInside,IdEntryGate,IdWristband")] ClientEntry clientEntry)
 {
     if (ModelState.IsValid)
     {
         db.Entry(clientEntry).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.IdEntryGate = new SelectList(db.EntryGate, "Id", "Id", clientEntry.IdEntryGate);
     ViewBag.IdWristband = new SelectList(db.Wristband, "Id", "Id", clientEntry.IdWristband);
     return(View(clientEntry));
 }
コード例 #12
0
ファイル: ServerCore.cs プロジェクト: LootKeeper/SocketChat
        public void HandleAuth(object sender, Message msg)
        {
            ClientEntry entry = sender as ClientEntry;

            if (_anons.TryRemove(entry.Ip, out entry))
            {
                if (_users.TryAdd(msg.Id, entry))
                {
                    Console.WriteLine($"{msg.Text} entered to chat");
                }
            }
        }
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ClientEntry clientEntry = db.ClientEntry.Find(id);

            if (clientEntry == null)
            {
                return(HttpNotFound());
            }
            return(View(clientEntry));
        }
コード例 #14
0
 /// <summary>
 /// send data to the client.
 /// </summary>
 /// <param name="clientEntry"></param>
 /// <param name="data">Data as string to send to the client.</param>
 private void SendResponse(ClientEntry clientEntry, string data)
 {
     if (clientEntry.Client != null)
     {
         try
         {
             clientEntry.Client.GetStream().BeginWrite(System.Text.Encoding.UTF8.GetBytes(data), 0, data.Length, this.OnWriteDoneCallback, clientEntry);
         }
         catch (Exception /*e*/)
         {
             Output.WriteLine("Server: Exception on writing to network stream.");
             this.DisconnectClient(clientEntry);
         }
     }
 }
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ClientEntry clientEntry = db.ClientEntry.Find(id);

            if (clientEntry == null)
            {
                return(HttpNotFound());
            }
            ViewBag.IdEntryGate = new SelectList(db.EntryGate, "Id", "Id", clientEntry.IdEntryGate);
            ViewBag.IdWristband = new SelectList(db.Wristband, "Id", "Id", clientEntry.IdWristband);
            return(View(clientEntry));
        }
コード例 #16
0
ファイル: ServerCore.cs プロジェクト: LootKeeper/SocketChat
        public void HandleLogOut(object sender, Message msg)
        {
            if (_users.Any(user => user.Key == msg.Id))
            {
                ClientEntry user = null;
                _users.Remove(msg.Id, out user);
                user.ShutDown(this, null);
                user.OnMessageRecieve -= HandleMessage;
                Console.WriteLine($"{msg.Name} logout");
            }

            ClientEntry entry = null;

            if (_anons.TryRemove((sender as ClientEntry).Ip, out entry))
            {
                entry.ShutDown(this, null);
                entry.OnMessageRecieve -= HandleMessage;
            }
        }
        public ActionResult Create([Bind(Include = "Id,Date,IsGoesInside,IdEntryGate,IdWristband")] ClientEntry clientEntry)
        {
            clientEntry.Date = DateTime.Now;
            if (ModelState.IsValid)
            {
                db.ClientEntry.Add(clientEntry);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            var entryGates = db.EntryGate.Select(n => new
            {
                Id          = n.Id,
                Description = n.Attraction.Name + " " + n.Id
            });

            ViewBag.IdEntryGate = new SelectList(entryGates, "Id", "Description", clientEntry.IdEntryGate);
            ViewBag.IdWristband = new SelectList(db.Wristband, "Id", "Id", clientEntry.IdWristband);
            return(View(clientEntry));
        }
コード例 #18
0
ファイル: ClientList.cs プロジェクト: tandj1116/pandorasbox3
        private void lst_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            if (lst.SelectedIndices.Count == 1)
            {
                ClientEntry current = null;

                try
                {
                    current = m_Clients[int.Parse(lst.SelectedItems[0].SubItems[5].Text)] as ClientEntry;
                }
                catch {}

                m_Client = current;
            }
            else
            {
                m_Client = null;
            }

            EnableButtons();
        }
コード例 #19
0
    /// <summary>
    /// On TCP client connects to listen socket...
    /// </summary>
    /// <param name="result">Operation result is given into this callback</param>
    private void OnTcpClientConnectingCallback(IAsyncResult result)
    {
        if (result != null)
        {
            Output.WriteLine("Server: Incoming client.");

            // accept the client...
            var clientEntry = new ClientEntry();
            this.ConnectedClients.Add(clientEntry);
            clientEntry.Client = this.TcpListenSocket.EndAcceptTcpClient(result);

            // continue awaiting new clients on listen socket...
            this.AwaitIncomingClient();

            // say welcome to the client...
            Output.WriteLine("Server: Welcome client...");
            this.SendResponse(clientEntry, "WELCOME");

            // start receiving data from the client's network stream...
            this.ReceiveRequest(clientEntry);
        }
    }
コード例 #20
0
    /// <summary>
    /// simple server logics acting on received data.
    /// </summary>
    /// <param name="clientEntry"></param>
    /// <param name="dataString">the request to react on.</param>
    private void ReactOnRequest(ClientEntry clientEntry, string dataString)
    {
        // ---------------------------------------------------------------------------
        // THIS IS A SIMPLE SERVER LOGICS THAT ACTS ON RECEIVED DATA...
        // ---------------------------------------------------------------------------

        // send back "OK" followed by the upper-string if the string can be converted to upper,
        // else send "NOT CONVERTED".
        if (dataString.ToUpper() == dataString)
        {
            Output.WriteLine("Server: Client data string is not convertible. Send NOT CONVERTED.");
            this.SendResponse(clientEntry, "NOT CONVERTED");
        }
        else
        {
            Output.WriteLine("Server: converting client's data string and send it back...");
            this.SendResponse(clientEntry, "OK");
            this.SendResponse(clientEntry, dataString.ToUpper());
        }
        // ---------------------------------------------------------------------------
        // DONE
        // ---------------------------------------------------------------------------
    }
コード例 #21
0
    /// <summary>
    /// receive from given client...
    /// </summary>
    /// <param name="clientEntry"></param>
    private void ReceiveRequest(ClientEntry clientEntry)
    {
        if (clientEntry.Client.Connected)
        {
            Output.WriteLine("Server: Awaiting request...");

            Array.Clear(clientEntry.TcpData, 0, clientEntry.TcpData.Length);
            try
            {
                clientEntry.Client.GetStream().BeginRead(clientEntry.TcpData, 0, clientEntry.TcpData.Length, this.OnReadDoneCallback, clientEntry);
            }
            catch (Exception /*e*/)
            {
                Output.WriteLine("Server: Exception on reading from network stream.");
                this.DisconnectClient(clientEntry);
            }
        }
        else
        {
            Output.WriteLine("Server: Can't receive from client socket due socket is not connected.");
            this.DisconnectClient(clientEntry);
        }
    }
コード例 #22
0
            private bool TryDequeue(out ClientEntry entry)
            {
                if (_disposedValue)
                {
                    throw new ObjectDisposedException(nameof(ClientPool));
                }

                bool result;

                // ReSharper disable once AssignmentInConditionalExpression
                while (result = _clients.TryDequeue(out entry))
                {
                    // validate the client before returning it
                    if (entry.Client.Connected && entry.StartMillis + entry.MaxLiveTime >= (Environment.TickCount & int.MaxValue))
                    {
                        break;
                    }

                    entry.DisposeClient();
                }

                return(result);
            }
コード例 #23
0
            public bool TryDequeue(out ClientEntry entry)
            {
                if (disposedValue)
                {
                    throw new ObjectDisposedException(nameof(ClientPool));
                }

                bool result;

                while (result = _clients.TryDequeue(out entry))
                {
                    // validate the client before returning it
                    if (entry.Client.Connected && entry.StartMillis + entry.MaxLiveTime >= (Environment.TickCount & int.MaxValue))
                    {
                        break;
                    }
                    else
                    {
                        entry.DisposeClient();
                    }
                }

                return(result);
            }
コード例 #24
0
            public int Compare(object x, object y)
            {
                var X = x as ListViewItem;
                var Y = y as ListViewItem;

                if (X == null || Y == null)
                {
                    return(0);
                }

                ClientEntry item1 = null;
                ClientEntry item2 = null;

                try
                {
                    var s1 = int.Parse(X.SubItems[5].Text);
                    var s2 = int.Parse(Y.SubItems[5].Text);

                    item1 = m_Clients[s1] as ClientEntry;
                    item2 = m_Clients[s2] as ClientEntry;
                }
                catch
                { }

                if (item1 == null || item2 == null)
                {
                    return(0);
                }

                if (!m_Ascending)
                {
                    var temp = item1;
                    item1 = item2;
                    item2 = temp;
                }

                switch (m_Column)
                {
                case 0:                         // Name

                    return(string.Compare(item1.Name, item2.Name));

                case 1:                         // Account

                    return(string.Compare(item1.Account, item2.Account));

                case 2:                         // Map

                    return(item1.Map.CompareTo(item2.Map));

                case 3:                         // Location

                    var cmp = item1.X.CompareTo(item2.Y);

                    if (cmp == 0)
                    {
                        return(item1.Y.CompareTo(item2.Y));
                    }
                    else
                    {
                        return(cmp);
                    }

                case 4:                         // Login time

                    return(DateTime.Compare(item1.LoggedIn, item2.LoggedIn));

                case 5:                         // Serial

                    return(item1.Serial.CompareTo(item2.Serial));
                }

                return(0);
            }
コード例 #25
0
        public void CommandConnect(object sender, CommandEventArgs e)
        {
            if (e.Parameters.Length == 0)
            {
                e.Reply("I'm connected to the following servers:");
                foreach (ClientEntry clientEntry in Bot.Clients)
                {
                    IrcClient client = clientEntry.Client;
                    switch (client.State)
                    {
                    case IrcClientState.Disconnected:
                        e.Reply(string.Format("{0} - \u00034offline\u000F.", client.NetworkName));
                        break;

                    case IrcClientState.Connecting:
                        e.Reply(string.Format("{0} - \u00038connecting\u000F.", client.NetworkName));
                        break;

                    case IrcClientState.SslHandshaking:
                        e.Reply(string.Format("{0} - \u00038establishing TLS connection\u000F.", client.NetworkName));
                        break;

                    case IrcClientState.SaslAuthenticating:
                        e.Reply(string.Format("{0} - \u00038authenticating\u000F.", client.NetworkName));
                        break;

                    case IrcClientState.Registering:
                        e.Reply(string.Format("{0} - \u00038logging in\u000F.", client.NetworkName));
                        break;

                    case IrcClientState.Online:
                        if (client.Channels.Count > 1)
                        {
                            e.Reply(string.Format("{0} - \u00039online\u000F; on channels \u0002{1}\u000F.", client.NetworkName, string.Join("\u000F, \u0002", client.Channels.Select(c => c.Name))));
                        }
                        else if (client.Channels.Count == 1)
                        {
                            e.Reply(string.Format("{0} - \u00039online\u000F; on channel \u0002{1}\u000F.", client.NetworkName, client.Channels.First().Name));
                        }
                        else
                        {
                            e.Reply(string.Format("{0} - \u00039online\u000F.", client.NetworkName));
                        }
                        break;

                    default:
                        e.Reply(string.Format("{0} - {1}.", client.NetworkName, client.State));
                        break;
                    }
                }
            }
            else
            {
                foreach (ClientEntry clientEntry in Bot.Clients)
                {
                    IrcClient client = clientEntry.Client;
                    if (client.Address.Equals(e.Parameters[0], StringComparison.OrdinalIgnoreCase) || (client.Extensions.NetworkName != null && client.Extensions.NetworkName.Equals(e.Parameters[0], StringComparison.OrdinalIgnoreCase)))
                    {
                        if (client.State != IrcClientState.Disconnected)
                        {
                            e.Reply(string.Format("I'm already connected to \u0002{0}\u000F.", client.Address));
                        }
                        else
                        {
                            e.Reply(string.Format("Reconnecting to \u0002{0}\u000F.", client.Address));
                            client.Connect(clientEntry.Address, clientEntry.Port);
                        }
                        return;
                    }
                }

                e.Reply(string.Format("Connecting to \u0002{0}\u000F.", e.Parameters[0]));

                var network = new ClientEntry(e.Parameters[0])
                {
                    Address   = e.Parameters[0],
                    Port      = 6667,
                    Nicknames = new[] { e.Client.Me.Nickname },
                    Ident     = e.Client.Me.Ident,
                    FullName  = e.Client.Me.FullName
                };
                Bot.AddNetwork(network);
                network.Connect();
            }
        }
コード例 #26
0
        public async void SendCheck(string message, IrcClient originConnection, IrcMessageTarget origin)
        {
            foreach (string channelName in this.Targets)
            {
                string[] fields = channelName.Split(new char[] { '/' }, 2);
                if (fields.Length == 1)
                {
                    fields = new string[] { "*", fields[0] }
                }
                ;

                IEnumerable <ClientEntry> clients;
                if (fields[0] == "*")
                {
                    clients = Bot.Clients;
                }
                else
                {
                    ClientEntry client = Bot.Clients.FirstOrDefault(c => fields[0].Equals(c.Client.Extensions.NetworkName, StringComparison.OrdinalIgnoreCase) || fields[0].Equals(c.Client.Address, StringComparison.OrdinalIgnoreCase));
                    if (client == default(ClientEntry))
                    {
                        return;
                    }
                    clients = new ClientEntry[] { client };
                }

                foreach (ClientEntry clientEntry in clients)
                {
                    IrcClient client = clientEntry.Client;
                    if (fields[1] == "*")
                    {
                        if (client == originConnection)
                        {
                            foreach (IrcChannel channel in client.Channels.Where(_channel => _channel != origin))
                            {
                                channel.Say(message);
                            }
                        }
                        else
                        {
                            foreach (IrcChannel channel in client.Channels)
                            {
                                channel.Say(message);
                            }
                        }
                    }
                    else if (client.IsChannel(fields[1]) && (client != originConnection || !client.CaseMappingComparer.Equals(fields[1], origin)))
                    {
                        client.Send("PRIVMSG " + fields[1] + " :" + message);
                    }
                    else
                    {
                        IrcUser user;
                        if ((client != originConnection || !client.CaseMappingComparer.Equals(fields[1], origin)) && client.Users.TryGetValue(fields[1], out user) && await Bot.CheckPermissionAsync(user, this.Key + ".receive"))
                        {
                            client.Send("PRIVMSG " + fields[1] + " :" + message);
                        }
                    }
                }
            }
        }
コード例 #27
0
ファイル: Lock.cs プロジェクト: coder0xff/Alterity
        Lock(object[] dataObjects, int timeoutMilliseconds, Action action)
        {
            requiredThread = System.Threading.Thread.CurrentThread;
            syncRoot = 0;

            if (dataObjects.Length == 0)
            {
                succeeded = true;
                hasLock = true;
                isWaiting = false;
            }
            else
            {
                ((IDataObject)dataObjects[0]).GetDataStore().UploadScript(CreateLockScript, CreateLockScriptSha1);
                ((IDataObject)dataObjects[0]).GetDataStore().UploadScript(DecrementAndDestroyScript, DecrementAndDestroyScriptSha1);

                foreach (object dataObject in dataObjects)
                    if (!(dataObject is IDataObject))
                        throw new ArgumentException("All the objects must be IDataObjects created by Doredis");

                succeeded = false;
                hasLock = false;
                isWaiting = true;
                signal = new ManualResetEvent(true);
                Timer timeoutTimer = new Timer(_ => Fail(), null, timeoutMilliseconds, Timeout.Infinite);
                try
                {
                    foreach (IDataObject dataObject in dataObjects)
                    {
                        DataStoreShard dataStore = dataObject.GetDataStoreShard(dataObject.GetAbsolutePath());
                        Action<string> signalHandler = (string dontCare) => { signal.Set(); };
                        if (!clientEntries.ContainsKey(dataStore)) clientEntries[dataStore] = new ClientEntry(dataStore, signalHandler);
                        clientEntries[dataStore].Add(dataObject);
                    }
                    while (true)
                    {
                        try
                        {
                            lock (syncRoot)
                            {
                                signal.Reset();
                                if (isWaiting)
                                {
                                    hasLock = TryLock();
                                    if (hasLock)
                                    {
                                        isWaiting = false;
                                    }
                                }
                                else
                                    break;
                            }
                            if (hasLock)
                            {
                                succeeded = true;
                                action();
                                break;
                            }
                        }
                        finally
                        {
                            lock (syncRoot)
                            {
                                if (hasLock)
                                {
                                    hasLock = false;
                                    FreeLock();
                                }
                            }
                        }
                        //if the server that held the lock goes down, this'll prevent all the others from waiting forever
                        //eventually, the lock will expire
                        signal.WaitOne(keepAliveExpireTime * 1000);
                    }
                }
                finally
                {
                    foreach (var entry in clientEntries)
                    {
                        entry.Value.Dispose();
                    }
                    timeoutTimer.Dispose();
                    signal.Dispose();
                }
            }
        }
コード例 #28
0
 /// <summary>
 /// Disconnect client with given client info
 /// </summary>
 /// <param name="clientEntry"></param>
 private void DisconnectClient(ClientEntry clientEntry)
 {
     Output.WriteLine("Server: Closing server side client socket.");
     clientEntry.Client.Close();
     this.ConnectedClients.Remove(clientEntry);
 }