private void AuthentificateUserCallback(IAsyncResult result)
        {

            try
            {
                var request = (WebRequest)result.AsyncState;
                var response = (WebResponse)request.EndGetResponse(result);
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    if (reader.ReadToEnd().Equals("OK"))
                        _callback.Invoke(AuthentificationCode.LoginSuccessed);
                    else
                        _callback.Invoke(AuthentificationCode.InvalidCredentials);
                }
            }
            catch (Exception ex)
            {
                if (ex is WebException)
                {
                    var response = ((HttpWebResponse)((WebException)ex).Response);
                    if (response.StatusCode == HttpStatusCode.Unauthorized)
                        _callback.Invoke(AuthentificationCode.InvalidCredentials);
                    else
                        _callback.Invoke(AuthentificationCode.ServerNotFound);
                }
                else if (ex is ArgumentException)
                {
                    _callback.Invoke(AuthentificationCode.ServerNotFound);
                }
            }

        }
        private void getMostUrgentProjectsCallback(IAsyncResult asyncResult)
        {
            GetMostUrgentProjectsAsyncState asyncState =
                asyncResult.AsyncState as GetMostUrgentProjectsAsyncState;
            WebRequest request = asyncState.Request;
            Action<List<Project>, Exception> viewModelCallback = asyncState.ViewModelCallback;

            try
            {
                WebResponse response = request.EndGetResponse(asyncResult);
                List<Project> projects = null;
                string json = null;

                using (var stream = response.GetResponseStream())
                {
                    using (var reader = new StreamReader(stream))
                    {
                        json = reader.ReadToEnd().Trim();
                    }
                }

                projects = EntityTranslator.TranslateGenericSearchResultsToProjects(json);
                DispatcherHelper.CheckBeginInvokeOnUI(() => viewModelCallback(projects, null));
            }
            catch (Exception ex)
            {
                DispatcherHelper.CheckBeginInvokeOnUI(() => viewModelCallback(null, ex));
            }
        }
Exemplo n.º 3
1
 private void ResponseCallback(IAsyncResult result)
 {
     HttpWebRequest request  = (HttpWebRequest)result.AsyncState;
     //request.GetResponse().GetResponseStream();
     if (OnUpload != null)
         OnUpload(this);
 }
Exemplo n.º 4
1
        private void ResponseCallback(IAsyncResult result)
        {
            var state = (List<object>) result.AsyncState;
            var googleRequest = (GooglePlaceSearchRequest) state[1];
            if (result.IsCompleted)
            {
                try
                {
                    var request = (HttpWebRequest)state[0];
                    var response = (HttpWebResponse)request.EndGetResponse(result);
                    var responseStream = response.GetResponseStream();
                    var serializer = new DataContractJsonSerializer(typeof(GooglePlaceSearchResponse));
                    var googleSearchResponse = (GooglePlaceSearchResponse)serializer.ReadObject(responseStream);
                    if (googleSearchResponse.Status == GoogleMapsSearchStatus.OK)
                        SearchForPlacesAsyncCompleted(googleSearchResponse, googleRequest);
                    else if (googleSearchResponse.Status == GoogleMapsSearchStatus.ZERO_RESULTS)
                        SearchForPlacesAsyncNotFound(googleSearchResponse, googleRequest);
                } catch(Exception e)
                {
                    if (SearchForPlacesAsyncFailed!= null)
                        SearchForPlacesAsyncFailed(e.Message, e);
                }
            } else
            {
                if (SearchForPlacesAsyncFailed != null)
                    SearchForPlacesAsyncFailed("For some reason request is not completed", null);

            }
        }
Exemplo n.º 5
1
 /// <summary>
 ///  回调委托
 /// </summary>
 /// <param name="ar">The ar.</param>
 /// Author  : 俞立钢
 /// Company : 绍兴标点电子技术有限公司
 /// Created : 2014-10-15 16:55:37
 private void AsyncCallback(IAsyncResult ar)
 {
     if (ar.IsCompleted)
     {
         HideProgress();
     }
 }
Exemplo n.º 6
1
        static void Begin1Callback(IAsyncResult result)
        {
            if (result.CompletedSynchronously)
            {
                return;
            }

            ChainedAsyncResult thisPtr = (ChainedAsyncResult)result.AsyncState;

            bool completeSelf = false;
            Exception completeException = null;

            try
            {
                completeSelf = thisPtr.Begin1Completed(result);
            }
            catch (Exception exception)
            {
                completeSelf = true;
                completeException = exception;
            }

            if (completeSelf)
            {
                thisPtr.Complete(false, completeException);
            }
        }
Exemplo n.º 7
1
 protected override void RecieveCallback(IAsyncResult Result)
 {
     DatagramState Dstate = (DatagramState)Result.AsyncState;
     int bytes = 0;
     Socket S = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     S.Bind(new IPEndPoint(IPAddress.Any, 0));
     Socket past = Dstate.ClientSocket;
     Dstate.ClientSocket = S;
     try
     {
         bytes = past.EndReceiveFrom(Result, ref Dstate.EndPoint);
     }
     catch (Exception e)
     {
         Next.Set();
         Send("Respect the buffer size which is " + DatagramState.BufferSize.ToString(), Dstate);
         return;
     }
     if (bytes>0)
     {
         string content = "";
         Dstate.MsgBuilder.Append(Encoding.ASCII.GetString(Dstate.Buffer, 0, bytes));
         content = Dstate.MsgBuilder.ToString();
         Next.Set();
         try
         {
             string r = Calculate(content).ToString();
             Send(r, Dstate);
         }
         catch (Exception e)
         {
             Send(e.Message, Dstate);
         }
     }
 }
Exemplo n.º 8
1
        private void OnReceive(IAsyncResult ias)
        {
            try
            {
                var length = base.EndReceive(ias);

                if (length < 6)
                {
                    throw new Exception("Connection closed");
                }

                var receivedBytes = new byte[length];
                Array.Copy(_buffer, receivedBytes, length);

                HandlePacket(receivedBytes);
            }
            catch
            {
                Destroy();
            }
            finally
            {
                Destroy();
            }
        }
Exemplo n.º 9
1
        private void ReadCallback(IAsyncResult result)
        {
            try
            {
                if (this._isClosed)
                {
                    this._clientSocket.Close();
                    return;
                }
                var networkStream = this._clientSocket.GetStream();

                var read = networkStream.EndRead(result);
                if (read == 0)
                {
                    this._networkStream.Close();
                    this._clientSocket.Close();
                    return;
                }

                var buffer = (byte[]) result.AsyncState;
                var data = Constants.Encoding.GetString(buffer, 0, read);

                this.DataReceived?.Invoke(((IPEndPoint) this._clientSocket.Client.RemoteEndPoint).Address, data);

                this.WaitForRequest();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error: "+ex.Message);
            }
        }
Exemplo n.º 10
1
        protected void onClientConnect(IAsyncResult res)
        {
            try
            {
                tcpConnection conn = new tcpConnection(listener_.EndAccept(res));
                IPEndPoint endPoint = (IPEndPoint)conn.socket.RemoteEndPoint;

                connections_.Add(Dns.GetHostEntry(endPoint.Address).HostName, conn);
                Console.WriteLine(
                    DateTime.Now.ToString() +
                    " new connection from " +
                    Dns.GetHostEntry(endPoint.Address).HostName);
            }
            catch (Exception e)
            {
                Console.WriteLine(
                    DateTime.Now.ToString() +
                    " new connection attempt failed: " +
                    e.Message);
            }
            finally
            {
                listener_.BeginAccept(new AsyncCallback(onClientConnect), null);
            }
        }
Exemplo n.º 11
1
        void OnReceive(IAsyncResult result)
        {
            try
            {
                if (result.IsCompleted)
                {
                    int bytesRead = socket.EndReceive(result);

                    if (bytesRead > 0)
                    {
                        byte[] read = new byte[bytesRead];
                        Array.Copy(buffer, 0, read, 0, bytesRead);

                        readHandler(this, read);
                        Begin(socket, readHandler, errorHandler);
                    }
                    else
                    {
                        // Disconnect
                    }
                }
            }
            catch (Exception e)
            {
                if (errorHandler != null)
                {
                    errorHandler(this, e);
                }
            }
        }
Exemplo n.º 12
1
        public void ListenerCallback(IAsyncResult result)
        {
            // HttpListener listener = (HttpListener)result.AsyncState;
            HttpListenerContext context;
            try
            {
                context = listener.EndGetContext(result);
            }
            catch
            {
                // stop メソッドで例外が発生するので、対処
                return;
            }
            // var content = listener.GetContext();
            var req = context.Request;
            var url = req.RawUrl;
            var res = context.Response;

            string text = url.Replace("/metro/method/", "");
            text = System.Web.HttpUtility.UrlDecode(text);
            listBox1.Items.Add("受信:" +  text);

            var output = new StreamWriter(res.OutputStream);
            output.WriteLine(string.Format("called {0}", url));
            output.Close();

            // 次の受信の準備
            listener.BeginGetContext(ListenerCallback, listener);
        }
 public IBrokeredMessage EndReceive(IAsyncResult result) {
     var msg = client.EndReceive(result);
     if (msg != null) {
         return new BrokeredMessageWrapper(msg);
     }
     return null;
 }
 private static void CheckForUpdateCallback(IAsyncResult ar)
 {
     object[] asyncState = (object[]) ar.AsyncState;
     HttpWebRequest request = (HttpWebRequest) asyncState[0];
     SynchronizationContext context = (SynchronizationContext) asyncState[1];
     Ini ini = null;
     Exception exception = null;
     bool flag = false;
     try
     {
         HttpWebResponse response = (HttpWebResponse) request.EndGetResponse(ar);
         ini = new Ini();
         using (TextReader reader = new StreamReader(response.GetResponseStream()))
         {
             ini.Read(reader);
         }
         FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(Application.ExecutablePath);
         ini.Set("Version", "CurrentVersion", versionInfo.ProductVersion);
     }
     catch (WebException exception2)
     {
         exception = exception2;
         flag = true;
     }
     catch (Exception exception3)
     {
         exception = exception3;
     }
     context.Send(new SendOrPostCallback(CheckForUpdatesDialog.ShowCheckResult), new object[] { exception, flag, ini });
 }
Exemplo n.º 15
1
        private void ReadCallback(IAsyncResult result)
        {
            NetworkStream networkStream = _clientSocket.GetStream();
            try
            {
                int read = networkStream.EndRead(result);
                if (read == 0)
                {
                    _networkStream.Close();
                    _clientSocket.Close();
                    return;
                }

                byte[] buffer = result.AsyncState as byte[];
                string data = Encoding.Default.GetString(buffer, 0, read);
                handler.OnClientRead(_clientSocket, data);

            }
            catch (Exception ex)
            {
                throw;
            }

            this.WaitForRequest();
        }
Exemplo n.º 16
1
        public void ReceiveMessage(IAsyncResult ar)
        {
            try
            {
                if (!IsConnected())
                {
                    Dispose();
                    return;
                }

                int bufferLength = netStream.EndRead(ar);
                string messageReceived = Encoding.ASCII.GetString(data, 0, bufferLength);
                if (!messageReceived.IsNullOrWhiteSpace() && commandQueue.Count < 5)
                {
                    commandQueue.Enqueue(messageReceived);
                    CheckForNameMessage(messageReceived);
                    netStream.Flush();
                }
                netStream.BeginRead(data, 0, bufferSize, ReceiveMessage, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Exemplo n.º 17
1
        // Called when we receive data from the client
        private void OnReceive(IAsyncResult res)
        {
            try
            {
                m_received += m_connection.EndReceive(res);

                // if we haven't gotten enough for a full request yet, receive again
                if (m_received < s_policyRequestString.Length)
                {
                    m_connection.BeginReceive(m_buffer, m_received, s_policyRequestString.Length - m_received, SocketFlags.None, new AsyncCallback(OnReceive), null);
                    return;
                }

                // make sure the request is valid
                string request = System.Text.Encoding.UTF8.GetString(m_buffer, 0, m_received);
                if (StringComparer.InvariantCultureIgnoreCase.Compare(request, s_policyRequestString) != 0)
                {
                    m_connection.Close();
                    return;
                }

                // send the policy
                m_connection.BeginSend(m_policy, 0, m_policy.Length, SocketFlags.None, new AsyncCallback(OnSend), null);
            }
            catch (SocketException)
            {
                m_connection.Close();
            }
        }
Exemplo n.º 18
1
 /// <summary>
 ///  回调委托
 /// </summary>
 /// <param name="ar">The ar.</param>
 /// Author  : 俞立钢
 /// Company : 绍兴标点电子技术有限公司
 /// Created : 2014-10-15 16:55:37
 private void AsyncCallbackCreate(IAsyncResult ar)
 {
     if (ar.IsCompleted)
     {
         HidePrgCreate();
     }
 }
Exemplo n.º 19
1
 private void MethodCompleted(IAsyncResult asyncResult)
 {
     if (asyncResult == null)
     {
         return;
     }
 }
		public void EndSend(IAsyncResult result)
		{
			if (_queueClient != null)
				_queueClient.EndSend(result);
			else
				_sender.EndSend(result);
		}
 /**
  * EchoCallback
  * Callback function to implement the Async call
  *
  */
 static void EchoCallback(IAsyncResult ar)
 {
     // Get the service object from the IAsyncResult object and get the response
     EchoServicePortTypeClient echosv = (EchoServicePortTypeClient)ar.AsyncState;
     echoStringResponse result = echosv.EndechoOperation(ar);
     Console.WriteLine("CLIENT>> The async answer is '" + result.echoResponse + "'");
 }
Exemplo n.º 22
1
        private void RespCallback(IAsyncResult asynchronousResult)
        {
            try
            {
                // State of request is asynchronous.
                RequestState myRequestState = (RequestState)asynchronousResult.AsyncState;
                HttpWebRequest myHttpWebRequest2 = myRequestState.request;
                myRequestState.response = (HttpWebResponse)myHttpWebRequest2.EndGetResponse(asynchronousResult);

                // Read the response into a Stream object.
                Stream responseStream = myRequestState.response.GetResponseStream();
                myRequestState.streamResponse = responseStream;

                // Begin the Reading of the contents of the HTML page and print it to the console.
                IAsyncResult asynchronousInputRead = responseStream.BeginRead(myRequestState.BufferRead, 0, RequestState.BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
            }
            catch (WebException e)
            {
                // Need to handle the exception                
                if (this.OnError != null)
                {
                    this.OnError(new FeedErrorEventArgs(this.GetType().Name, e));
                }                      
            }
        }
Exemplo n.º 23
1
		public void EndCommit (IAsyncResult ar)
		{
			if (ar != this)
				throw new ArgumentException ("The IAsyncResult parameter must be the same parameter as returned by BeginCommit.", "asyncResult");

			EndCommitInternal (asyncResult);
		}
Exemplo n.º 24
1
        /// <summary>
        /// AcceptCallback是回调函数
        /// </summary>
        /// <param name="ar"></param>
        public static void AcceptCallback(IAsyncResult ar)
        {
            // 接收连接后,按照前面的定义会执行该函数,首先就是让主线程继续往下执行
            allDone.Set();
            count++;
            Console.WriteLine("连接已经建立");

            try
            {
                //将接收的连接传递进来
                Socket listener = (Socket)ar.AsyncState;

                //调用EndAccept方法表示连接已经建立,建立的连接就是该方法的返回的对象
                Socket handler = listener.EndAccept(ar);

                //保存当前会话的Socket信息
                StateObject state = new StateObject();

                state.socket = handler;

                //这里又出现了类似的定义。可以看出,BeginReceive函数的参数和同步里面Receive函数的参数前面是相同的
                //只是后面多出了两个:定义在BeginReceive函数执行完毕以后所要执行的操作
                //这里定义的是ReadCallback函数
                handler.BeginReceive(state.buffer, 0, StateObject.bufferSize, 0,
                    new AsyncCallback(ReadCallback), state);

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                _iLog.Error(ex.Message);
            }
        }
Exemplo n.º 25
1
        private void OnAccept(IAsyncResult ar)
        {
            try
            {
                Socket clientSocket;
                try
                {
                    clientSocket = serverSocket.EndAccept(ar);
                }
                catch (ObjectDisposedException)
                {
                    return;
                }

                // Once the client connects then start receiving the commands from it
                clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None,
                    new AsyncCallback(OnReceive), clientSocket);

                // Start listening for more clients
                serverSocket.BeginAccept(new AsyncCallback(OnAccept), null);
            }
            catch (SocketException)
            {
            }
            catch (Exception ex)
            {
                PodcasterUtilities.KLIKException(ex);
            }
        }
Exemplo n.º 26
1
        public static void ReadCallback(IAsyncResult ar)
        {
            // Retrieve the state object and the handler socket from the asynchronous state object.
            StateObject state = (StateObject)ar.AsyncState;
            Socket handler = state.workSocket;

            int bytesRead = 0;

            try
            {
                bytesRead = handler.EndReceive(ar);
            }
            catch (Exception e)
            {
                Console.Write(e);
            }
            //int bytesRead = state.buffer.Length;

            if (bytesRead > 0)
            {

                string clientMsg = WebSocket.AnalyticData(state.buffer, bytesRead);

                Console.WriteLine("接受到客户端数据:" + clientMsg);
                Send(handler, clientMsg);

                //接收下一条消息(因为这是一个递归的调用,所以这样就可以一直接收消息了)
                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);

                //JavaScriptSerializer js = new JavaScriptSerializer();
                //反序列化前台传过来的JSON字符串,变为ClientInfo对象
                //ClientInfo clientInfo = js.Deserialize<ClientInfo>(clientMsg);
                // if (clientInfo != null)
            }
        }
Exemplo n.º 27
1
	    private void EndGetHostAddress(IAsyncResult asyncResult)
        {
	        var state = (State) asyncResult.AsyncState;
	        try
	        {
	            var addresses = Dns.EndGetHostAddresses(asyncResult);
	            var endPoint = new IPEndPoint(addresses[0], 123);

	            var socket = new UdpClient();
	            socket.Connect(endPoint);
	            socket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 500);
	            socket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 500);
	            var sntpData = new byte[SntpDataLength];
	            sntpData[0] = 0x1B; // version = 4 & mode = 3 (client)

	        	var newState = new State(socket, endPoint, state.GetTime, state.Failure);
	        	var result = socket.BeginSend(sntpData, sntpData.Length, EndSend, newState);
				RegisterWaitForTimeout(newState, result);
	        }
	        catch (Exception)
	        {
                // retry, recursion stops at the end of the hosts
                BeginGetDate(state.GetTime, state.Failure);
	
	        }
	    }
Exemplo n.º 28
1
        private void EndCheckEncryption(IAsyncResult result)
        {
            var id = (PeerId) result.AsyncState;
            try
            {
                byte[] initialData;
                EncryptorFactory.EndCheckEncryption(result, out initialData);

                if (initialData != null && initialData.Length == HandshakeMessage.HandshakeLength)
                {
                    var message = new HandshakeMessage();
                    message.Decode(initialData, 0, initialData.Length);
                    handleHandshake(id, message);
                }
                else if (initialData.Length > 0)
                {
                    throw new Exception("Argh. I can't handle this scenario. It also shouldn't happen. Ever.");
                }
                else
                {
                    PeerIO.EnqueueReceiveHandshake(id.Connection, id.Decryptor, handshakeReceivedCallback, id);
                }
            }
            catch
            {
                id.Connection.Dispose();
            }
        }
Exemplo n.º 29
1
        private void WaitForConnectionCallBack(IAsyncResult iar)
        {
            try
            {
                // Get the pipe
                NamedPipeServerStream pipeServer = (NamedPipeServerStream) iar.AsyncState;
                // End waiting for the connection
                pipeServer.EndWaitForConnection(iar);

                StreamReader sr = new StreamReader(pipeServer);
                StreamWriter sw = new StreamWriter(pipeServer);


                var response = ProccesQueries(sr.ReadLine());
                sw.WriteLine(response);
                sw.Flush();
                pipeServer.WaitForPipeDrain();

                // Kill original sever and create new wait server
                pipeServer.Disconnect();
                pipeServer.Close();
                pipeServer = null;
                pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte,
                                                       PipeOptions.Asynchronous);

                // Recursively wait for the connection again and again....
                pipeServer.BeginWaitForConnection(WaitForConnectionCallBack, pipeServer);
            }
            catch (Exception e)
            {
                Log.Debug("Pipe server error", e);
            }
        }
Exemplo n.º 30
1
        void HandleContext(IAsyncResult ar)
        {
            //
            // Get the context
            //
            HttpListenerContext ctx = null;
            try {
                ctx = _listener.EndGetContext (ar);
            }
            catch (Exception ex) {
                Console.WriteLine (ex);
            }

            //
            // Get the next request
            //
            _listener.BeginGetContext (HandleContext, null);

            //
            // Process
            //
            if (ctx != null) {
                Process (ctx);
            }
        }
Exemplo n.º 31
0
 public GamerProfile EndGetProfile(IAsyncResult result)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 32
0
 public static string EndGetPartnerToken(IAsyncResult result)
 {
     throw new NotSupportedException();
 }
Exemplo n.º 33
0
 public static Gamer EndGetFromGamertag(IAsyncResult result)
 {
     throw new NotSupportedException();
 }
Exemplo n.º 34
0
 public GamerProfile EndGetProfile(IAsyncResult result)
 {
     return(new GamerProfile());
 }
Exemplo n.º 35
0
        private IEnumerable <GoogleAddress> ProcessResponseAsync(RequestState requestState, IAsyncResult result)
        {
            if (requestState.cancellationToken != null)
            {
                requestState.cancellationToken.Value.ThrowIfCancellationRequested();
            }

            try
            {
                using (var response = (HttpWebResponse)requestState.request.EndGetResponse(result))
                {
                    return(ProcessWebResponse(response));
                }
            }
            catch (GoogleGeocodingException)
            {
                //let these pass through
                throw;
            }
            catch (Exception ex)
            {
                //wrap in google exception
                throw new GoogleGeocodingException(ex);
            }
        }
 public override void EndWrite(IAsyncResult asyncResult) => _stream.EndWrite(asyncResult);
Exemplo n.º 37
0
        /// <summary>
        ///  поиск сервера
        /// </summary>
        private Socket findSocket(string ip)
        {
            textPole.Invoke((MethodInvoker) delegate
            {
                textPole.Text = "Connecting.";
            });
            //List<string> str = finds(ip);
            Socket temp = null;
            // получение домена локальной сети
            string local = ip.Substring(0, ip.LastIndexOf(".")) + ".";
            int    i     = 0;

            while (true)
            {
                // создание сокета
                temp = new Socket(AddressFamily.InterNetwork,
                                  SocketType.Stream, ProtocolType.Tcp);
                // пробуем подключиться
                IAsyncResult result = temp.BeginConnect(IPAddress.Parse(ip), Port, null, null);
                // ожидание результата
                bool success = result.AsyncWaitHandle.WaitOne(500, true);

                if (!success)
                {
                    // если неудачно, закрыть сокет
                    temp.Close();
                    textPole.Invoke((MethodInvoker) delegate
                    {
                        textPole.Text += ".";
                    });
                }
                else
                {
                    try
                    {
                        // если удачно, то попытка завершить подключение
                        temp.EndConnect(result);
                        textPole.Invoke((MethodInvoker) delegate
                        {
                            textPole.Text = "Connected to " + temp.RemoteEndPoint + "\n";
                        });
                        // сигнал, что подключение есть
                        ConnectDone.Set();
                        break;
                    }
                    catch
                    {
                        // сервер отверг подключение, закрыть сокет
                        temp.Close();
                    }
                }
            }
            //while(true)
            //{
            //    // создание сокета
            //    temp = new Socket(AddressFamily.InterNetwork,
            //        SocketType.Stream, ProtocolType.Tcp);
            //    // пробуем подключиться
            //    IAsyncResult result = temp.BeginConnect(IPAddress.Parse(local + i++), Port, null, null);
            //    // ожидание результата
            //    bool success = result.AsyncWaitHandle.WaitOne(500, true);

            //    if (!success)
            //    {
            //        // если неудачно, закрыть сокет
            //        temp.Close();
            //        textPole.Invoke((MethodInvoker)delegate
            //        {
            //            textPole.Text += ".";
            //        });
            //    }
            //    else
            //    {
            //        try
            //        {
            //            // если удачно, то попытка завершить подключение
            //            temp.EndConnect(result);
            //            textPole.Invoke((MethodInvoker)delegate
            //            {
            //                textPole.Text = "Connected to " + temp.RemoteEndPoint + "\n";
            //            });
            //            // сигнал, что подключение есть
            //            ConnectDone.Set();
            //            break;
            //        }
            //        catch
            //        {
            //            // сервер отверг подключение, закрыть сокет
            //            temp.Close();
            //        }

            //    }
            //    // начать поиск с начального адреса
            //    if (i == 255)
            //    {
            //        i = 0;
            //        textPole.Invoke((MethodInvoker)delegate
            //        {
            //            textPole.Text = "Connecting.";
            //        });
            //    }
            //}

            ConnectDone.Set();
            return(temp);
        }
Exemplo n.º 38
0
        public static string RunConsoleApp(string strAppPath, string strParams,
                                           string strStdInput, AppRunFlags f)
        {
            if (strAppPath == null)
            {
                throw new ArgumentNullException("strAppPath");
            }
            if (strAppPath.Length == 0)
            {
                throw new ArgumentException("strAppPath");
            }

            bool bStdOut = ((f & AppRunFlags.GetStdOutput) != AppRunFlags.None);

            RunProcessDelegate fnRun = delegate()
            {
                Process pToDispose = null;
                try
                {
                    ProcessStartInfo psi = new ProcessStartInfo();

                    psi.CreateNoWindow         = true;
                    psi.FileName               = strAppPath;
                    psi.WindowStyle            = ProcessWindowStyle.Hidden;
                    psi.UseShellExecute        = false;
                    psi.RedirectStandardOutput = bStdOut;

                    if (strStdInput != null)
                    {
                        psi.RedirectStandardInput = true;
                    }

                    if (!string.IsNullOrEmpty(strParams))
                    {
                        psi.Arguments = strParams;
                    }

                    Process p = Process.Start(psi);
                    pToDispose = p;

                    if (strStdInput != null)
                    {
                        EnsureNoBom(p.StandardInput);

                        p.StandardInput.Write(strStdInput);
                        p.StandardInput.Close();
                    }

                    string strOutput = string.Empty;
                    if (bStdOut)
                    {
                        strOutput = p.StandardOutput.ReadToEnd();
                    }

                    if ((f & AppRunFlags.WaitForExit) != AppRunFlags.None)
                    {
                        p.WaitForExit();
                    }
                    else if ((f & AppRunFlags.GCKeepAlive) != AppRunFlags.None)
                    {
                        pToDispose = null;                         // Thread disposes it

                        Thread th = new Thread(delegate()
                        {
                            try { p.WaitForExit(); p.Dispose(); }
                            catch (Exception) { Debug.Assert(false); }
                        });
                        th.Start();
                    }

                    return(strOutput);
                }
#if DEBUG
                catch (Exception ex) { Debug.Assert(ex is ThreadAbortException); }
#else
                catch (Exception) { }
#endif
                finally
                {
                    try { if (pToDispose != null)
                          {
                              pToDispose.Dispose();
                          }
                    }
                    catch (Exception) { Debug.Assert(false); }
                }

                return(null);
            };

            if ((f & AppRunFlags.DoEvents) != AppRunFlags.None)
            {
                List <Form> lDisabledForms = new List <Form>();
                if ((f & AppRunFlags.DisableForms) != AppRunFlags.None)
                {
                    foreach (Form form in Application.OpenForms)
                    {
                        if (!form.Enabled)
                        {
                            continue;
                        }

                        lDisabledForms.Add(form);
                        form.Enabled = false;
                    }
                }

                IAsyncResult ar = fnRun.BeginInvoke(null, null);

                while (!ar.AsyncWaitHandle.WaitOne(0))
                {
                    Application.DoEvents();
                    Thread.Sleep(2);
                }

                string strRet = fnRun.EndInvoke(ar);

                for (int i = lDisabledForms.Count - 1; i >= 0; --i)
                {
                    lDisabledForms[i].Enabled = true;
                }

                return(strRet);
            }

            return(fnRun());
        }
Exemplo n.º 39
0
 /// <devdoc>
 /// <para>Returns a <see cref='System.IO.Stream'/> object that is used for writing data to the resource
 ///    identified by <see cref='System.Net.WebRequest.RequestUri'/>
 ///    .</para>
 /// </devdoc>
 public virtual Stream EndGetRequestStream(IAsyncResult asyncResult)
 {
     throw ExceptionHelper.MethodNotImplementedException;
 }
Exemplo n.º 40
0
	///<summary>Called when there's an incoming client connection waiting to be accepted.</summary>
	///<param name="ar">The result of the asynchronous operation.</param>
	public abstract void OnAccept(IAsyncResult ar);
Exemplo n.º 41
0
 public string EndGetInitializeData(IAsyncResult result)
 {
     return(this.Call(() => this.Service.EndGetInitializeData(result)));
 }
Exemplo n.º 42
0
 public override void EndWrite(IAsyncResult asyncResult)
 {
     throw new NotSupportedException();
 }
Exemplo n.º 43
0
 public override int EndRead(IAsyncResult asyncResult)
 {
     return(TaskToApm.End <int>(asyncResult));
 }
Exemplo n.º 44
0
 /// <devdoc>
 ///    <para>Returns a WebResponse object.</para>
 /// </devdoc>
 public virtual WebResponse EndGetResponse(IAsyncResult asyncResult)
 {
     throw ExceptionHelper.MethodNotImplementedException;
 }
 /// <summary>
 /// Waits for the pending asynchronous read to complete.
 /// </summary>
 public override int EndRead(IAsyncResult asyncResult)
 {
     ThrowIfDisposed();
     return(m_streamBase.EndRead(asyncResult));
 }
Exemplo n.º 46
0
 public override void EndWrite(IAsyncResult asyncResult)
 {
     TaskToApm.End(asyncResult);
 }
Exemplo n.º 47
0
        /// <summary>
        /// Callback method for asynchronous requests.
        /// </summary>
        private void GetResponseAsyncCompleted(IAsyncResult ar)
        {
            GetResponseDelegate caller = (GetResponseDelegate)ar.AsyncState;

            GetResponseAsyncCompletedCore(() => caller.EndInvoke(ar));
        }
 /// <summary>
 /// Ends an asynchronous write operation.
 /// </summary>
 public override void EndWrite(IAsyncResult asyncResult)
 {
     ThrowIfDisposed();
     m_streamBase.EndWrite(asyncResult);
 }
Exemplo n.º 49
0
 public int EndExecuteNonQuery(IAsyncResult asyncResult)
 {
     return(((Func <int>)(asyncResult as AsyncResult).AsyncDelegate).EndInvoke(asyncResult));
 }
Exemplo n.º 50
0
        private void ReceiveData(object userState)
        {
            User      user   = (User)userState;
            TcpClient client = user.client;

            while (!Instance.ISExit)
            {
                string receive                = string.Empty;
                ReceiveMessageDelegate d      = new ReceiveMessageDelegate(ReceiveMessage);
                IAsyncResult           result = d.BeginInvoke(user, out receive, null, null);
                //使用轮询方式来判断异步操作是否完成
                while (!result.IsCompleted)
                {
                    if (Instance.ISExit)
                    {
                        break;
                    }
                    Thread.Sleep(50);
                    //Thread.Sleep(100);
                }
                //获取Begin方法的返回值和所有输入/输出参数
                d.EndInvoke(out receive, result);
                if (receive.Length == 0 || receive == null)
                {
                    if (!Instance.ISExit)
                    {
                        //日志
                        Console.WriteLine(string.Format("与{0}失去联系,已终止接收该用户信息", user.IP));
                        RemoveUser(user);
                    }
                    break;
                }

                string        aswer  = string.Empty;
                CommandManage manage = new CommandManage();
                try
                {
                    Console.WriteLine("接受:" + receive);

                    aswer = manage.Proc(receive);

                    Console.WriteLine("应答:" + aswer);
                }
                catch
                {
                    manage.CloseUser = true;
                }

                //foreach (User target in Instance.UserList)
                //{
                //    if (target.IP == client.Client.RemoteEndPoint.ToString())
                //    {
                //        AsyncSendToClient(target, aswer);
                //    }
                //}

                AsyncSendToClient(user, aswer);

                if (manage.CloseUser)
                {
                    this.RemoveUser(user);
                }
            }
        }
 protected void AspCompatEndProcessRequest(IAsyncResult result)
 {
 }
Exemplo n.º 52
0
 public object EndExecuteScalar(IAsyncResult asyncResult)
 {
     return(((Func <object>)(asyncResult as AsyncResult).AsyncDelegate).EndInvoke(asyncResult));
 }
 public List <GithubRepository> EndGetRepositoriesFromUser(IAsyncResult asyncResult)
 {
     throw new NotImplementedException();
 }
 protected void AsyncPageEndProcessRequest(IAsyncResult result)
 {
 }
 public GithubAuthorization EndCreateAuthorizationToken(IAsyncResult asyncResult)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 56
0
        /// <summary>
        /// 检查是否有更新的返回及处理
        /// </summary>
        /// <param name="result"></param>
        private void EndGetCheckResponse(IAsyncResult result)
        {
            UpdateInfo ui = new UpdateInfo();

            ui.UpdateFilesInfo = new List <UpdateFileInfo>();
            try
            {
                //结束异步请求,获取结果
                HttpWebRequest webRequest  = (HttpWebRequest)result.AsyncState;
                WebResponse    webResponse = webRequest.EndGetResponse(result);
                //把输出结果转化为Person对象
                Stream       stream = webResponse.GetResponseStream();
                StreamReader sr     = new StreamReader(stream, Encoding.UTF8);
                string       upInfo = sr.ReadToEnd();

                //开始解析更新文件的xml
                if (upInfo.Trim().Length > 0)
                {
                    XmlDocument xmldoc = new XmlDocument();
                    xmldoc.LoadXml(upInfo);

                    XmlNode root = xmldoc.SelectSingleNode("//files");
                    if (root.HasChildNodes)
                    {
                        ui.FilesTotalSize     = int.Parse(root.Attributes["totalsize"].Value);
                        ui.FilesTotalSizeUnit = root.Attributes["unit"].Value;

                        XmlNodeList xnl = root.ChildNodes;
                        foreach (XmlNode xn in xnl)
                        {
                            UpdateFileInfo  ufi            = new UpdateFileInfo();
                            string          ufileVersion   = xn.Attributes["version"].Value;
                            string[]        ufileVerInfo   = ufileVersion.Split(new char[] { '.' });
                            FileVersionInfo fileVer        = FileVersionInfo.GetVersionInfo(xn.Attributes["name"].Value);
                            string          oldFileVersion = fileVer.FileVersion;
                            string[]        oldFileVerInfo = oldFileVersion.Split(new char[] { '.' });
                            //以下开始比较文件版本号。如果更新文件中的文件版本号大于本地的文件版本号,则下载更新,否则,不下载此文件更新
                            if (int.Parse(ufileVerInfo[0]) > int.Parse(oldFileVerInfo[0]) || int.Parse(ufileVerInfo[1]) > int.Parse(oldFileVerInfo[1]) || int.Parse(ufileVerInfo[2]) > int.Parse(oldFileVerInfo[2]) || int.Parse(ufileVerInfo[3]) > int.Parse(oldFileVerInfo[3]))
                            {
                                ufi.FileName    = xn.Attributes["name"].Value;
                                ufi.FileSize    = int.Parse(xn.Attributes["size"].Value);
                                ufi.FileVersion = xn.Attributes["version"].Value;
                                ui.UpdateFilesInfo.Add(ufi);
                            }
                        }
                        if (ui.UpdateFilesInfo.Count == 0)
                        {
                            ui.CheckResult = "您目前的版本已是最新";
                        }
                    }
                    else
                    {
                        ui.CheckResult = "您目前的版本已是最新";
                    }
                }
                else
                {
                    ui.CheckResult = "您目前的版本已是最新";
                }
            }
            catch (Exception e)
            {
                ui.CheckResult = "更新检查无法完成,请联系供应商";
            }
            this.uInfo = ui;
            if (sueh != null)
            {
                sueh(ui);
            }
        }
Exemplo n.º 57
0
 /// <summary>
 /// Finishes the asynchronous execution of the  DescribeEventTypes operation.
 /// </summary>
 ///
 /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeEventTypes.</param>
 ///
 /// <returns>Returns a  DescribeEventTypesResult from AWSHealth.</returns>
 /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/health-2016-08-04/DescribeEventTypes">REST API Reference for DescribeEventTypes Operation</seealso>
 public DescribeEventTypesResponse EndDescribeEventTypes(IAsyncResult asyncResult)
 {
     return(EndInvoke <DescribeEventTypesResponse>(asyncResult));
 }
 public List <GithubOrganization> EndGetOrganizationsFromUser(IAsyncResult asyncResult)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 59
0
 /// <summary>
 /// Finishes the asynchronous execution of the  DescribeEntityAggregates operation.
 /// </summary>
 ///
 /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeEntityAggregates.</param>
 ///
 /// <returns>Returns a  DescribeEntityAggregatesResult from AWSHealth.</returns>
 /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/health-2016-08-04/DescribeEntityAggregates">REST API Reference for DescribeEntityAggregates Operation</seealso>
 public DescribeEntityAggregatesResponse EndDescribeEntityAggregates(IAsyncResult asyncResult)
 {
     return(EndInvoke <DescribeEntityAggregatesResponse>(asyncResult));
 }
Exemplo n.º 60
0
        static void Main(string[] args)
        {
            try
            {
                if (args.Length == 2)
                {
                    int    port = 0;
                    string host = args[0];
                    try
                    {
                        port = Convert.ToInt32(args[1]);
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("");
                        Console.WriteLine("Could not parse port number.");
                        Console.WriteLine("");
                        Environment.Exit(2);
                    }

                    System.Net.Sockets.TcpClient tcpclient = new System.Net.Sockets.TcpClient();
                    IAsyncResult connection = tcpclient.BeginConnect(host, port, null, null);
                    System.Threading.WaitHandle waithandle = connection.AsyncWaitHandle;
                    tcpclient.SendTimeout = 3000;

                    try
                    {
                        if (!connection.AsyncWaitHandle.WaitOne(tcpclient.SendTimeout, false))
                        {
                            tcpclient.Close();
                            throw new TimeoutException();
                        }

                        tcpclient.EndConnect(connection);
                        Console.WriteLine("");
                        Console.WriteLine("Successfully connected to server.");
                        Console.WriteLine("");
                        Environment.Exit(1);
                    }
                    catch (TimeoutException)
                    {
                        Console.WriteLine("");
                        Console.WriteLine("The connection attempt timed out.");
                        Console.WriteLine("");
                        Environment.Exit(2);
                    }
                    catch (SocketException)
                    {
                        Console.WriteLine("");
                        Console.WriteLine("Connection actively refused.");
                        Console.WriteLine("");
                    }
                    finally
                    {
                        waithandle.Close();
                    }
                }
                else
                {
                    throw new ArgumentOutOfRangeException();
                }
            }
            catch (ArgumentOutOfRangeException)
            {
                Console.WriteLine("");
                Console.WriteLine("Invalid arguments");
                Console.WriteLine("");
                Environment.Exit(2);
            }
        }