コード例 #1
0
        public override void Operation()
        {
            try
            {
                // Connect to the remote endpoint.
                Socketv4.BeginConnect(new IPEndPoint(IPAddress.Loopback, Config.Port),
                                      ConnectCallback, Socketv4);
                _connectDone.WaitOne();

                // Send test data to the remote device.
                Send(Socketv4, Message);
                _sendDone.WaitOne();

                // Receive the response from the remote device.
                Receive(Socketv4);
                _receiveDone.WaitOne();

                // Write the response to the console.
                //Console.WriteLine("Response received : {0}", response);

                // Release the socket.
                Socketv4.Shutdown(SocketShutdown.Both);
                Socketv4.Close();
            }
            catch (Exception e)
            {
                ErrorUtil.WriteError(e).GetAwaiter().GetResult();
            }
        }
コード例 #2
0
        protected override void ConnectCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.

                // Complete the connection.
                if (ar.AsyncState is Socket client)
                {
                    client.EndConnect(ar);
                }
                else
                {
                    throw new ArgumentException(nameof(ar));
                }
                //Console.WriteLine("Socket connected to {0}", client.RemoteEndPoint.ToString());

                // Signal that the connection has been made.
                _connectDone.Set();
            }
            catch (Exception e)
            {
                ErrorUtil.WriteError(e).GetAwaiter().GetResult();
            }
        }
コード例 #3
0
        public override void Operation()
        {
            while (true)
            {
                try
                {
                    while (true)
                    {
                        _allDone.Reset();

                        // Start an asynchronous socket to listen for connections.
                        Socketv4.BeginAccept(
                            AcceptCallback,
                            Socketv4);

                        // Wait until a connection is made before continuing.
                        _allDone.WaitOne();
                    }
                }
                catch (Exception e)
                {
                    Message.Body = e;
                    ErrorUtil.WriteError(e).GetAwaiter().GetResult();
                }
                Socketv4.Close();
            }
            // ReSharper disable once FunctionNeverReturns
        }
コード例 #4
0
        protected override void SendCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.

                // Complete sending the data to the remote device.
                if (ar.AsyncState is Socket client)
                {
                    //Receive(client);

                    client.EndSend(ar);
                    //.WriteLine("Sent {0} bytes to server.", bytesSent);
                }
                else
                {
                    throw new ArgumentException(nameof(ar));
                }
                // Signal that all bytes have been sent.
                _sendDone.Set();
            }
            catch (Exception e)
            {
                ErrorUtil.WriteError(e).GetAwaiter().GetResult();
            }
        }
コード例 #5
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                var services = ServiceController.GetServices();

                var host = services.FirstOrDefault(tmp => tmp.ServiceName == "MFVolumeService");
                if (host is null || host.Status != ServiceControllerStatus.Running)
                {
                    MessageBox.Show("MFVolumeService未启用!请先启动MFVolumeService服务!", "错误", MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                    Environment.Exit(0);
                }

                foreach (var service in Config.Services)
                {
                    CbGroup.Items.Add(service.Nickname);
                    var flag = true;
                    foreach (var serviceName in service.Services)
                    {
                        var serv = services.FirstOrDefault(tmp => tmp.ServiceName == serviceName);
                        if (serv == null)
                        {
                            throw new NullReferenceException();
                        }
                        if (serv.Status == ServiceControllerStatus.Running)
                        {
                            continue;
                        }
                        flag = false;
                        break;
                    }

                    service.Enabled = flag;
                }

                LblServiceStatus.Content += Config.Enabled ? "启用" : "关闭";
                LblActivate.Content      += Config.Activation ? "启用" : "关闭";
                LblKmsServer.Content     += Config.KmsServer;
                CbGroup.SelectedIndex     = 0;
            }
            catch (Exception exception)
            {
                ErrorUtil.WriteError(exception).GetAwaiter().GetResult();
            }

            Workers.WorkerReportsProgress      = true;
            Workers.WorkerSupportsCancellation = true;
            Workers.DoWork             += DoProgress;
            Workers.ProgressChanged    += ProgressChanged;
            Workers.RunWorkerCompleted += ProgressCompleted;
        }
コード例 #6
0
        public void Listen()
        {
            TcpListener listener = null;
            TcpClient   client   = null;

            try
            {
                int port = IPUtil.DefaultPort;
                listener = new TcpListener(IPUtil.GetLocalIpAddress(), port);
                listener.Start();

                _log.InfoFormat("Waiting for a connection on port: {0} ", port);

                while (_listen)
                {
                    if (listener.Pending())
                    {
                        client = listener.AcceptTcpClient();
                        NetworkCommunicator networkCommunicator = new NetworkCommunicator(client);
                        _log.InfoFormat("Client {0} connected.", networkCommunicator.RemoteEndPoint);

                        //acknowledge client is able to join this game
                        networkCommunicator.SendData(MessageConstants.ServerAvailable);

                        string data = networkCommunicator.ReceiveData();
                        if (data == MessageConstants.CloseConnection)
                        {
                            networkCommunicator.Dispose();
                            _log.InfoFormat("Closed client connection - client was just finding servers.");
                        }
                        else if (data == MessageConstants.JoinGame)
                        {
                            OnPlayerJoined(networkCommunicator);
                        }
                    }
                    Thread.Sleep(100);
                }
            }
            catch (Exception ex)
            {
                ErrorUtil.WriteError(ex);
                throw;
            }
            finally
            {
                listener.Stop();
            }
        }
コード例 #7
0
 public MainWindow()
 {
     InitializeComponent();
     try
     {
         Config = FileUtil
                  .ImportObj <ConfigModel>($"{ConfigModel.ConfigPath}\\{ConfigModel.ConfigName}")
                  .GetAwaiter().GetResult();
     }
     catch (Exception e)
     {
         ErrorUtil.WriteError(e).GetAwaiter().GetResult();
     }
     Workers   = new BackgroundWorker();
     BgwWindow = new BackgroundWorkWindow();
 }
コード例 #8
0
        private void TogBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Workers.RunWorkerAsync((TogBtn.IsChecked ?? false, Config, CbGroup.SelectedItem.ToString()));
                BgwWindow.ShowDialog();

                /*PbWait.IsIndeterminate = true;
                 * CbGroup.IsEnabled = false;
                 * TogBtn.IsEnabled = false;*/
            }
            catch (Exception exception)
            {
                ErrorUtil.WriteError(exception).GetAwaiter().GetResult();
            }
        }
コード例 #9
0
        protected override void Receive(Socket client)
        {
            try
            {
                // Create the state object.
                var state = new StateObject(client, Config);

                // Begin receiving the data from the remote device.
                client.BeginReceive(state.Buffer, 0, state.BufferSize, 0,
                                    ReceiveCallback, state);
            }
            catch (Exception e)
            {
                ErrorUtil.WriteError(e).GetAwaiter().GetResult();
            }
        }
コード例 #10
0
        protected override void SendCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                if (!(ar.AsyncState is Socket handler))
                {
                    throw new ArgumentException(nameof(ar));
                }
                // Complete sending the data to the remote device.
                handler.EndSend(ar);
                //Console.WriteLine($"Sent {bytesSent} bytes to client.");

                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }
            catch (Exception e)
            {
                ErrorUtil.WriteError(e).GetAwaiter().GetResult();
            }
        }
コード例 #11
0
        protected override void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the state object and the client socket
                // from the asynchronous state object.
                if (!(ar.AsyncState is StateObject state))
                {
                    throw new ArgumentException(nameof(ar));
                }
                var client = state.WorkSocket;

                // Read data from the remote device.
                state.ReceiveSize = client.EndReceive(ar);

                // Signal that the receive has been made.
                _receiveDone.Set();
            }
            catch (Exception e)
            {
                ErrorUtil.WriteError(e).GetAwaiter().GetResult();
            }
        }
コード例 #12
0
        protected override void ReceiveCallback(IAsyncResult ar)
        {
            // Retrieve the state object and the handler socket
            // from the asynchronous state object.
            if (!(ar.AsyncState is StateObject state))
            {
                return;
            }
            var handler = state.WorkSocket;

            // Read data from the client socket.
            state.ReceiveSize = handler.EndReceive(ar);

            if (state.ReceiveSize <= 0)
            {
                return;
            }
            // There  might be more data, so store the data received so far.

            /*state.Sb.Append(Encoding.ASCII.GetString(
             *  state.Buffer, 0, bytesRead));*/

            try
            {
                using (var msg = BinaryUtil.DeserializeObject <SocketMessage>(state.Buffer, 0, state.ReceiveSize))
                {
                    var response = SortSocketMessage(msg);
                    Send(handler, response);
                }
            }
            catch (Exception e)
            {
                ErrorUtil.WriteError(e).GetAwaiter().GetResult();
                throw;
            }
        }
コード例 #13
0
        public SocketMessage Operate()
        {
            var services = ServiceController.GetServices();

            foreach (var service in ServiceGroup.Services)
            {
                var controller = services.FirstOrDefault(tmp => tmp.ServiceName == service);
                if (controller is null)
                {
                    var exception = new NullReferenceException($"There is no : {service}");
                    ErrorUtil.WriteError(exception).GetAwaiter().GetResult();
                    continue;
                }
                if (ServiceGroup.Enabled)
                {
                    controller.Start();
                }
                else
                {
                    controller.Stop();
                }
            }
            return(new SocketMessage());
        }
コード例 #14
0
        private void ClientGameLoop(object client)
        {
            NetworkCommunicator networkCommunicator = (NetworkCommunicator)client;
            ManualResetEvent    sentDataThisTurn    = new ManualResetEvent(false);
            ManualResetEvent    endOfTurnWait       = new ManualResetEvent(false);

            try
            {
                string data = string.Empty;

                _playersThatSentDataThisTurnList.Add(sentDataThisTurn);
                _endOfTurnWaitList.Add(endOfTurnWait);
                _currentTurnClientActions.Add(new PlayerAction(networkCommunicator.RemoteEndPoint.ToString(), MessageConstants.PlayerActionNone));

                _log.InfoFormat("Client {0} connected running on thread: {1}, waiting for start game / 1st turn data", networkCommunicator.RemoteEndPoint, Thread.CurrentThread.ManagedThreadId);
                data = networkCommunicator.ReceiveData();
                bool readFromClient = false;

                if (data == MessageConstants.StartGame)
                {
                    readFromClient = true;
                    RunGame();
                    foreach (NetworkCommunicator clientPlayer in _players)
                    {
                        clientPlayer.SendData(MessageConstants.GameStarting);
                    }
                    _completeGameState.StartNewGame(_currentTurnClientActions);
                }

                // Loop to receive all the data sent by the client.
                // this is now the main game loop for the game - 1 thread per client
                bool gameIsOn = true;
                while (gameIsOn) //issue [B.2.3] of the design document
                {
                    if (readFromClient)
                    {
                        data = networkCommunicator.ReceiveData();
                    }
                    else
                    {
                        readFromClient = true;
                    }

                    foreach (PlayerAction action in _currentTurnClientActions)
                    {
                        if (action.PlayerID == networkCommunicator.RemoteEndPoint.ToString())
                        {
                            action.Action = data;
                        }
                    }
                    sentDataThisTurn.Set();

                    _gameStateProcessed.WaitOne();

                    networkCommunicator.SendData(_completeGameState.ToString());
                    endOfTurnWait.Set();
                    WaitHandle.WaitAll(_endOfTurnWaitArray); //issue [B.2.3] of the design document
                    _gameStateProcessed.Reset();
                }
            }
            catch (Exception ex)
            {
                ErrorUtil.WriteError(ex);
                throw;
            }
            finally
            {
                sentDataThisTurn.Close();
                endOfTurnWait.Close();
                networkCommunicator.Dispose();
            }
        }