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);
}
}
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);
}
}
}
/// <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();
}
}
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);
}
}
}
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);
}
}
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();
}
public IBrokeredMessage EndReceive(IAsyncResult result) {
var msg = client.EndReceive(result);
if (msg != null) {
return new BrokeredMessageWrapper(msg);
}
return null;
}
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);
}
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();
}
}
/// <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);
}
}
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);
}
}
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);
}
}
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)
}
}
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);
}
}
// 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();
}
}
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));
}
}
}
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 });
}
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);
}
}
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 void EndSend(IAsyncResult result)
{
if (_queueClient != null)
_queueClient.EndSend(result);
else
_sender.EndSend(result);
}
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);
}
}
/**
* 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 + "'");
}
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();
}
}
/// <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();
}
}
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);
}
}
private void MethodCompleted(IAsyncResult asyncResult)
{
if (asyncResult == null)
{
return;
}
}
private void ResponseCallback(IAsyncResult result)
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
//request.GetResponse().GetResponseStream();
if (OnUpload != null)
OnUpload(this);
}
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);
}
}
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));
}
}
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);
}
}
}