private void ContinueAsyncSend(object state) { // // FxCop: need to snapshot the address here, so we're sure that it's not changed between the permission // and the operation, and to be sure that IPAddress.ToString() is called and not some override that // always returns "localhost" or something. // Debug.Assert(asyncOp != null, "Null AsyncOp?"); AsyncStateObject stateObject = (AsyncStateObject)state; try { IPAddress addressSnapshot = Dns.GetHostAddresses(stateObject.hostName)[0]; (new NetworkInformationPermission(NetworkInformationAccess.Ping)).Demand(); InternalSend(addressSnapshot, stateObject.buffer, stateObject.timeout, stateObject.options, true); } catch (Exception e) { PingException pe = new PingException(SR.GetString(SR.net_ping), e); PingCompletedEventArgs eventArgs = new PingCompletedEventArgs(null, pe, false, asyncOp.UserSuppliedState); Finish(true); asyncOp.PostOperationCompleted(onPingCompletedDelegate, eventArgs); } }
public void BeginReceive() { var stateObject = new AsyncStateObject(m_socket); m_socket.BeginReceive( stateObject.ReceiveBuffer, 0, stateObject.ReceiveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveDataCallback), stateObject); }
//BeginReceiveのコールバック private void ReceiveDataCallback(System.IAsyncResult ar) { //状態オブジェクトの取得 AsyncStateObject so = (AsyncStateObject)ar.AsyncState; /* so.Socketとthis.socketの違いはあるか?*/ //読み込んだ長さを取得 int len = 0; try { len = so.Socket.EndReceive(ar); } catch (System.ObjectDisposedException) { FuncWhenClosed(remoteID); return; } catch (System.Net.Sockets.SocketException) { FuncWhenClosed(remoteID); return; } if (len == 0) { FuncWhenClosed(remoteID); return; } //受信したデータを蓄積する so.ReceivedData.Write(so.ReceiveBuffer, 0, len); if (so.Socket.Available == 0) { //最後まで受信した時 //受信したデータを文字列に変換 /*string str = System.Text.Encoding.UTF8.GetString( * so.ReceivedData.ToArray()); */ this.FuncWhenRecvd(remoteID, so.ReceivedData.ToArray()); so.ReceivedData.Close(); so.ReceivedData = new System.IO.MemoryStream(); } //再び受信開始 so.Socket.BeginReceive(so.ReceiveBuffer, 0, so.ReceiveBuffer.Length, System.Net.Sockets.SocketFlags.None, new System.AsyncCallback(ReceiveDataCallback), so); }
//データ受信スタート private void StartReceive(System.Net.Sockets.Socket soc) { AsyncStateObject so = new AsyncStateObject(soc); Connecting = true; //非同期受信を開始 soc.BeginReceive(so.ReceiveBuffer, 0, so.ReceiveBuffer.Length, System.Net.Sockets.SocketFlags.None, new System.AsyncCallback(ReceiveDataCallback), so); }
//データ受信スタート private void StartReceive(System.Net.Sockets.Socket soc) { AsyncStateObject so = new AsyncStateObject(soc); Console.WriteLine("buffer size is {0}", so.ReceiveBuffer.Length); //非同期受信を開始 soc.BeginReceive(so.ReceiveBuffer, 0, so.ReceiveBuffer.Length, System.Net.Sockets.SocketFlags.None, new System.AsyncCallback(this.ReceiveDataCallback), so); }
//BeginReceiveのコールバック private void ReceiveDataCallback(System.IAsyncResult ar) { try { //状態オブジェクトの取得 AsyncStateObject so = (AsyncStateObject)ar.AsyncState; //読み込んだ長さを取得 int len = 0; len = so.Socket.EndReceive(ar); //切断されたか調べる if (len <= 0) { //System.Console.WriteLine("切断されました。"); DisConnected(this, new DisConnectedArgs(server.RemoteEndPoint.ToString())); so.Socket.Close(); Connecting = false; return; } //受信したデータを蓄積する so.ReceivedData.Write(so.ReceiveBuffer, 0, len); if (so.Socket.Available == 0) { //最後まで受信した時 //受信したデータを文字列に変換 string str = System.Text.Encoding.UTF8.GetString( so.ReceivedData.ToArray()).Trim('\r', '\n'); //受信した文字列を表示 //System.Console.WriteLine(str); MessageReceived?.Invoke(this, new MessageReceivedArgs(server.RemoteEndPoint.ToString(), str)); so.ReceivedData.Close(); so.ReceivedData = new System.IO.MemoryStream(); } //再び受信開始 so.Socket.BeginReceive(so.ReceiveBuffer, 0, so.ReceiveBuffer.Length, System.Net.Sockets.SocketFlags.None, new System.AsyncCallback(ReceiveDataCallback), so); } catch (System.ObjectDisposedException) { //閉じた時 //System.Console.WriteLine("閉じました。"); DisConnected(this, new DisConnectedArgs(server.RemoteEndPoint.ToString())); Connecting = false; return; } }
private void ContinueAsyncSend(object state) { AsyncStateObject obj2 = (AsyncStateObject)state; try { IPAddress address = Dns.GetHostAddresses(obj2.hostName)[0]; new NetworkInformationPermission(NetworkInformationAccess.Ping).Demand(); this.InternalSend(address, obj2.buffer, obj2.timeout, obj2.options, true); } catch (Exception exception) { PingException error = new PingException(SR.GetString("net_ping"), exception); PingCompletedEventArgs arg = new PingCompletedEventArgs(null, error, false, this.asyncOp.UserSuppliedState); this.Finish(true); this.asyncOp.PostOperationCompleted(this.onPingCompletedDelegate, arg); } }
private void ContinueAsyncSend(object state) { Debug.Assert(_asyncOp != null, "Null AsyncOp?"); AsyncStateObject stateObject = (AsyncStateObject)state; try { IPAddress address = Dns.GetHostAddressesAsync(stateObject.HostName).GetAwaiter().GetResult()[0]; InternalSendAsync(address, stateObject.Buffer, stateObject.Timeout, stateObject.Options); } catch (Exception e) { PingException pe = new PingException(SR.net_ping, e); PingCompletedEventArgs eventArgs = new PingCompletedEventArgs(null, pe, false, _asyncOp.UserSuppliedState); Finish(); _asyncOp.PostOperationCompleted(_onPingCompletedDelegate, eventArgs); } }
private void SendAsync(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions options, object userToken) { if (string.IsNullOrEmpty(hostNameOrAddress)) { throw new ArgumentNullException("hostNameOrAddress"); } if (buffer == null) { throw new ArgumentNullException("buffer"); } if (buffer.Length > MaxBufferSize) { throw new ArgumentException(SR.net_invalidPingBufferSize, "buffer"); } if (timeout < 0) { throw new ArgumentOutOfRangeException("timeout"); } IPAddress address; if (IPAddress.TryParse(hostNameOrAddress, out address)) { SendAsync(address, timeout, buffer, options, userToken); return; } CheckStart(true); try { _cancelled = false; _asyncOp = AsyncOperationManager.CreateOperation(userToken); AsyncStateObject state = new AsyncStateObject(hostNameOrAddress, buffer, timeout, options, userToken); ThreadPool.QueueUserWorkItem(new WaitCallback(ContinueAsyncSend), state); } catch (Exception e) { Finish(true); throw new PingException(SR.net_ping, e); } }
private static void ReceiveDataCallback(IAsyncResult result) { //状態オブジェクトの取得 AsyncStateObject so = (AsyncStateObject)result.AsyncState; //読み込んだ長さを取得 int len = 0; try { len = so.Socket.EndReceive(result); } catch (System.ObjectDisposedException) { //閉じた時 System.Console.WriteLine("閉じました。"); return; } if (len <= 0) //切断された場合 { System.Console.WriteLine("切断されました。"); so.Socket.Close(); return; } //受信したデータを蓄積する so.ReceivedData.Write(so.ReceiveBuffer, 0, len); if (so.Socket.Available == 0) //最後まで受信した場合 //受信したデータを文字列に変換して表示 { string str = System.Text.Encoding.UTF8.GetString( so.ReceivedData.ToArray()); System.Console.Write(str); so.ReceivedData.Close(); so.ReceivedData = new System.IO.MemoryStream(); } //再び受信開始 so.Socket.BeginReceive(so.ReceiveBuffer, 0, so.ReceiveBuffer.Length, System.Net.Sockets.SocketFlags.None, new System.AsyncCallback(ReceiveDataCallback), so); }
public void SendAsync(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions options, object userToken) { IPAddress address; if (ValidationHelper.IsBlankString(hostNameOrAddress)) { throw new ArgumentNullException("hostNameOrAddress"); } if (buffer == null) { throw new ArgumentNullException("buffer"); } if (buffer.Length > 0xffdc) { throw new ArgumentException(SR.GetString("net_invalidPingBufferSize"), "buffer"); } if (timeout < 0) { throw new ArgumentOutOfRangeException("timeout"); } if (IPAddress.TryParse(hostNameOrAddress, out address)) { this.SendAsync(address, timeout, buffer, options, userToken); } else { this.CheckStart(true); try { this.cancelled = false; this.asyncOp = AsyncOperationManager.CreateOperation(userToken); AsyncStateObject state = new AsyncStateObject(hostNameOrAddress, buffer, timeout, options, userToken); ThreadPool.QueueUserWorkItem(new WaitCallback(this.ContinueAsyncSend), state); } catch (Exception exception) { this.Finish(true); throw new PingException(SR.GetString("net_ping"), exception); } } }
private void ReadCallback(IAsyncResult result) { try { int read = 0; lock (lockObject) { read = socket.EndReceive(result); } AsyncStateObject state = (AsyncStateObject)result.AsyncState; if (read != state.numBytesToRead) { isMessaging = false; } else if (isMessaging) { state.next(); } } catch (Exception e) { isMessaging = false; } }
private void ContinueAsyncSend(object state) { // FxCop: need to snapshot the address here, so we're sure that it's not changed between the permission // check and the operation, and to be sure that IPAddress.ToString() is called and not some override. Debug.Assert(_asyncOp != null, "Null AsyncOp?"); AsyncStateObject stateObject = (AsyncStateObject)state; try { IPAddress addressSnapshot = Dns.GetHostAddressesAsync(stateObject.HostName).GetAwaiter().GetResult()[0]; InternalSend(addressSnapshot, stateObject.Buffer, stateObject.Timeout, stateObject.Options, true); } catch (Exception e) { PingException pe = new PingException(SR.net_ping, e); PingCompletedEventArgs eventArgs = new PingCompletedEventArgs(null, pe, false, _asyncOp.UserSuppliedState); Finish(true); _asyncOp.PostOperationCompleted(_onPingCompletedDelegate, eventArgs); } }
private void SocketAccepted(IAsyncResult result) { Socket s; AsyncStateObject aso; try { s = listener.EndAcceptSocket(result); } catch { return; } if (s.Connected) { clients.Add(s); aso = new AsyncStateObject(s, bufferSize); BeginReceive(aso); if (ClientConnected != null) ClientConnected(s); } listener.BeginAcceptSocket(dlgSocketAccepted, listener); }
//------------------------------------------------------------------------- //データ受信スタート //------------------------------------------------------------------------- private static void StartReceive(System.Net.Sockets.Socket soc) { AsyncStateObject so = new AsyncStateObject(soc); //非同期受信を開始 soc.BeginReceive(so.ReceiveBuffer, 0, so.ReceiveBuffer.Length, System.Net.Sockets.SocketFlags.None, new System.AsyncCallback(ReceiveDataCallback), so); mTmpBuffer = new byte[0]; }