Exemplo n.º 1
0
        public async Task ListenToMessages(string recipientEmail, string alias)
        {
            Response.Headers["Cache-Control"]     = "no-cache"; // https://serverfault.com/a/801629
            Response.Headers["X-Accel-Buffering"] = "no";
            Response.ContentType     = "text/event-stream";
            await using var response = new StreamWriter(Response.Body);
            var clients = Inboxes.GetOrAdd(recipientEmail.ToLower(), _ => new List <ClientHandle>(4));
            var client  = new ClientHandle
            {
                Ip             = Request.Headers["X-Real-IP"].ToString(),
                Alias          = alias,
                RecipientEmail = recipientEmail.ToLower(),
                Response       = response
            };

            lock (clients)
                clients.Add(client);
            await response.WriteAsync("event: connected\ndata:\n\n");

            await response.FlushAsync();

            Logger.Information("Client connected {@cli}", new { client.Ip, client.Alias, client.RecipientEmail });
            await HttpContext.RequestAborted.AsTask();

            lock (clients)
                clients.Remove(client);
            Logger.Information("Client disconnected {@cli}", new { client.Ip, client.Alias, client.RecipientEmail });
        }
Exemplo n.º 2
0
    internal static void ConnectToServer(Action successfullCallback, Action <string> errorCallback)
    {
        ClientHandle.AddHandlers();
        PlayerId = 0;

        _successfullCallback = successfullCallback;
        _errorCallback       = errorCallback;

        Client.Instance.ConnectToServer();
    }
Exemplo n.º 3
0
 public void AnswerMatchFound(bool answer) //This is called from a button in the pop up either ACCEPT OR DECLINE
 {
     hasAnswered = true;
     if (answer)
     {
         UIObjects.Instance.matcfoundAcceptButton.transform.GetComponent <Image>().color = new Color(1, 152, 117, 1);
     }
     if (!answer)
     {
         UIObjects.Instance.MatchFoundUI.GetComponent <Canvas>().enabled = false;
         ClientHandle.MMState(new Packet());
     }
     ClientSend.MatchFoundAnswer(answer);
 }
Exemplo n.º 4
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            this.Resize += (ss, ee) => { this.Size = new System.Drawing.Size(475, 400); };

            if (!this.GetSettints())
            {
                return;                           //获取参数
            }
            this.client = new ClientHandle(user); //创建通信客户端
            this.client.OnDisconnencted += (ok) => { this.runInfo.BeginInvoke((MethodInvoker)(() => { this.runInfo.AppendText("系统连接断开。\r\n"); })); };
            this.client.OnEndLogin      += (r, m) => { this.runInfo.BeginInvoke((MethodInvoker)(() => { this.runInfo.AppendText(r ? "系统已经登录。\r\n" : "系统登录失败。\r\n"); })); };
            client.Login();

            //this.DetectInit();//初始化检测客户端
        }
Exemplo n.º 5
0
        private Task <Result <ClientHandle> > ConnectAsync(OperationContext context, MachineId machineId, MachineLocation machineLocation)
        {
            return(context.PerformOperationAsync(
                       Tracer,
                       async() =>
            {
                var hostInfo = machineLocation.ExtractHostInfo();
                var channel = new Channel(hostInfo.host, hostInfo.port ?? _configuration.Port, ChannelCredentials.Insecure);
                var client = channel.CreateGrpcService <T>(ClientFactory.Create(MetadataServiceSerializer.BinderConfiguration));
                var handle = new ClientHandle(client, channel, machineId, machineLocation);

                await channel.ConnectAsync(DateTime.UtcNow + _configuration.ConnectTimeout);
                return Result.Success(handle);
            }));
        }
    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
        else if (instance != this)
        {
            Debug.Log("Instance already exists, destroying object!");
            Destroy(this);
        }

        trackers          = new Tracker[14];
        panel             = new Panel();
        deviceStatusArray = new bool[5];
    }
Exemplo n.º 7
0
 private void ConnectServer()
 {
     try
     {
         string server = ConfigurationSettings.AppSettings["server"];
         string port   = ConfigurationSettings.AppSettings["port"];
         string user   = ConfigurationSettings.AppSettings["user"];
         Client = new ClientHandle(user);
         Client.OnRecvSendDetectData += this.RecvDetectData;
         Client.OnRecvUpdateRule     += this.RecvUpdateRule;
         Client.Login();
     }
     catch
     {
     }
 }
    // Initialize singleton and the server data
    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Debug.Log("This Instance of Client is already created!");
            Destroy(gameObject);
        }

        // Initialize this clients data
        ClientHandle.InitializeClientData();
    }
Exemplo n.º 9
0
 public void CancelUserTask(ClientHandle clientToken)
 {
     lock (syncLock)
     {
         var thandle = ReadyQueue.FirstOrDefault(th => th.Token.ID == clientToken.ID);
         if (thandle != null)             // in case task is still in queue only
         {
             thandle.task     = null;
             thandle.callback = null;
             thandle.Token    = null;
         }
         else             // in case thread is running the task - try aborting the thread to cancel the operation (rude behavior)
         {
             //int itemCount = Instance.ReadyQueue.Count;
             TaskItem taskItem = null;
             lock (criticalLock)
             {
                 taskItem = Pool.FirstOrDefault(task => task.taskHandle.Token.ID == clientToken.ID);
             }
             if (taskItem != null)
             {
                 lock (taskItem)                     // only item need the locking
                 {
                     if (taskItem.taskState != TaskState.completed)
                     // double check - in case by the time this lock obtained callback already happened
                     {
                         taskItem.taskState = TaskState.aborted;
                         Debug.Log("Task Aborted: " + taskItem.taskHandle.Token.ID);
                         taskItem.taskHandle.callback = null;                             // stop callback
                     }
                     if (taskItem.taskState == TaskState.aborted)                         // this does not need criticalLock
                     {
                         try
                         {
                             taskItem.handler.Abort();                                 // **** it does not work ****
                             taskItem.handler.Priority     = System.Threading.ThreadPriority.BelowNormal;
                             taskItem.handler.IsBackground = true;
                         }
                         catch { }
                     }
                 }
             }
         }
     }
 }
Exemplo n.º 10
0
        private async void ListenAsync()
        {
            while (_listener.IsStarted)
            {
                WebSocket websocket;

                try
                {
                    websocket = await _listener.AcceptWebSocketAsync(_cts.Token).ConfigureAwait(false);

                    if (websocket == null)
                    {
                        continue;
                    }
                }
                catch (Exception e)
                {
                    Program.Logger.Error("Failed to accept websocket connection", e);
                    continue;
                }

                var client       = new TClient();
                var clientHandle = new ClientHandle(() =>
                {
                    lock (_clientsSync)
                    {
                        _clients.Remove(client);
                        _clientsCache = null;
                    }
                });

                client.Open(clientHandle, websocket, _cts.Token);

                lock (_clientsSync)
                {
                    _clients.Add(client);
                    _clientsCache = null;
                }
            }
        }
Exemplo n.º 11
0
    // Start is called before the first frame update
    void Awake()
    {
        // Setup Singleton
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }

        // Dependencies
        connectionController = GetComponent <ConnectionStarter>();
        chatController       = GetComponent <ChatController>();

        // Position the connect window
        connectionMenu.transform.localPosition = Vector3.zero;

        // Initialize server and Client dictionaries
        ClientHandle.InitializeClientData();
    }
Exemplo n.º 12
0
        public void HandleConnection(int id, ClientHandle clientHandle)
        {
            string serializedGameState = GameStateLoader.Serialize(gameState);

            clientHandle.Send(serializedGameState);
        }
Exemplo n.º 13
0
 public void GoToMap()
 {
     ClientHandle.HandleLobbyPacket(null);
 }
Exemplo n.º 14
0
 internal ClientQueueHandle(Packet receivedPacket, ClientHandle handle)
 {
     ReceivedPacket = receivedPacket;
     Handle         = handle;
 }
Exemplo n.º 15
0
 // This is the "Server." ListenThread waits for connections and initial client handling.
 // It spins off ClientThreads for every connection.
 private void ListenThread()
 {
     while(!_stopThreads)
     {
         try
         {
             // This is a blocking operation. When a client connects, it is passed to c.
             TcpClient c = _listener.AcceptTcpClient();
             Console.WriteLine("Client connected: " + c.Client.RemoteEndPoint);
             // Create a new client thread for this new client
             Thread t = new Thread(ClientThread);
             // Create a client handle to store the thread and the client, and give it the next id.
             ClientHandle ch = new ClientHandle(t, c, _clientIdNext++);
             if(ClientConnectedEvent !=  null)
                 ClientConnectedEvent(this, new ClientEventArgs(c, ch.ClientId));
             // start the client thread, and pass the client handle to the new thread.
             t.Start(ch);
             // send the latest object to the client
             SendObjectToClientHandle(ch);
             // add the client to the list of clients
             _clients.Add(ch);
         }
         catch (SocketException se)
         {
             if(se.ErrorCode == 10004)
                 return;
             throw new Exception(se.Message, se);
         }
         catch (Exception e)
         {
             throw new Exception(e.Message, e);
         }
         Thread.Sleep(1);
     }
 }
Exemplo n.º 16
0
 private void InitializeClient()
 {
     ClientHandle.InitializeClientPacketHandlers();
 }
Exemplo n.º 17
0
 public void HandleDisconnection(int id, ClientHandle clientHandle)
 {
     ThreadManager.ExecuteOnMainThread(() => { onConnection.Invoke(new LeaveGameCommand(id)); });
 }
Exemplo n.º 18
0
        // send an object to the client handle
        private void SendObjectToClientHandle(ClientHandle ch)
        {
            // Panic if the DataObject is null
            if(DataObject == null)
            {
                throw new Exception("Attempted SendObjectToClientHandle with no DataObject");
            }

            // mark the client as dead if it disconnected.
            if(ch.TcpClient.Connected == false)
            {
                // client is disconnected, mark for removal
                Console.WriteLine("Client is disconnected, marking for removal.");
                // TODO: Fire an event for the disconnected client
                if(ClientDisconnectedEvent != null)
                    ClientDisconnectedEvent(this, new ClientEventArgs(ch.TcpClient, ch.ClientId));
                ch.IsDead = true;
                return;
            }

            Console.WriteLine("SendObjectToClientHandle: " + ch.TcpClient.Client.RemoteEndPoint + " (" + ch.ClientId + ")");
            Console.WriteLine(DataObject);

            // Create the formatter
            SoapFormatter sf = new SoapFormatter();
            try
            {
                // Serialize the object into the TcpClient stream. This sends the object to the client.
                sf.Serialize(ch.TcpClient.GetStream(), DataObject);
                // Flush the stream
                ch.TcpClient.GetStream().Flush();
            }
            catch (System.IO.IOException)
            {
                // IO/socket exceptions mean that the intended client is probably dead, so lets remove
                // the client from our list.
                if (ClientDisconnectedEvent != null)
                    ClientDisconnectedEvent(this, new ClientEventArgs(ch.TcpClient, ch.ClientId));
                ch.IsDead = true;
            }
            catch (SocketException)
            {
                if (ClientDisconnectedEvent != null)
                    ClientDisconnectedEvent(this, new ClientEventArgs(ch.TcpClient, ch.ClientId));
                ch.IsDead = true;
            }
            catch (System.Xml.XmlException xmle)
            {
                Console.WriteLine("SendObjectToClientHandle: EXCEPTION: " + xmle.Message);
            }
            catch (Exception e)
            {
                throw new Exception("Error sending object to client: " + e.Message, e);
            }
        }