public async Task<bool> Open(string address = null, int port = -1) { try { IPEndPoint server = new IPEndPoint(IPAddress.Parse(_address), _port); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.SocketFlags = SocketFlags.None; args.RemoteEndPoint = server; var awaitable = new SocketAwaitable(args); awaitable.OnCompleted(() => { RaiseConnected(); //Flush(); //Receive(); }); _socket = new Socket(server.AddressFamily, SocketType.Stream, ProtocolType.Tcp); await _socket.ConnectAsync(awaitable); return awaitable.IsCompleted; } catch (Exception ex) { RaiseError(ex); throw; } }
public static IAwaitable SendAsync(this Socket socket, byte[] buffer) { var args = new SocketAsyncEventArgs(); args.SetBuffer(buffer); var awaitable = new SocketAwaitable(args); return socket.SendAsync(awaitable); }
public async Task<bool> Close() { try { if (_socket != null && _socket.Connected) { await Flush(); _socket.Shutdown(SocketShutdown.Both); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); var awaitable = new SocketAwaitable(args); awaitable.OnCompleted(() => { RaiseDisconnected(); // cancel pending receives }); await _socket.DisconnectAsync(awaitable); return !awaitable.IsCompleted; } return false; } catch (Exception ex) { RaiseError(ex); throw; } }
private static SocketAwaitable ReceiveAsync(this Socket socket, SocketAwaitable awaitable) { awaitable.Reset(); if (!socket.ReceiveAsync(awaitable.EventArgs)) awaitable.IsCompleted = true; return awaitable; }
public PacketTransmitter(Socket socket) { m_socket = socket; var socketEventArgs = new SocketAsyncEventArgs(); m_buffer = new byte[4096]; socketEventArgs.SetBuffer(m_buffer, 0, 0); m_socketAwaitable = new SocketAwaitable(socketEventArgs); }
public static SocketAwaitable SendAsync(this Socket socket, SocketAwaitable awaitable) { awaitable.Reset(); if (!socket.SendAsync(awaitable.m_eventArgs)) awaitable.m_wasCompleted = true; return awaitable; }
public static SocketAwaitable SendAsync(this Socket socket, SocketAwaitable awaitable) { awaitable.Reset(); if (!socket.SendAsync(awaitable.m_eventArgs)) { awaitable.m_wasCompleted = true; } return(awaitable); }
public void TestInitialization() { // Default values. var awaitable = new SocketAwaitable(); Assert.IsNull(awaitable.AcceptSocket); var awaiter = awaitable.GetAwaiter(); Assert.IsTrue(awaiter.IsCompleted); Assert.AreEqual(awaiter.GetResult(), SocketError.Success); }
public void TestBuffer() { // Default buffer values. var awaitable = new SocketAwaitable(); Assert.IsNotNull(awaitable.Buffer.Array); Assert.AreEqual(awaitable.Buffer.Array.Length, 0); Assert.AreEqual(awaitable.Buffer.Offset, 0); Assert.AreEqual(awaitable.Buffer.Count, 0); // Default transferred values. Assert.IsNotNull(awaitable.Transferred.Array); Assert.AreEqual(awaitable.Transferred.Array.Length, 0); Assert.AreEqual(awaitable.Transferred.Offset, 0); Assert.AreEqual(awaitable.Transferred.Count, 0); // Assign a null buffer. var nullBuffer = default(ArraySegment<byte>); Assert.IsNull(nullBuffer.Array); awaitable.Buffer = nullBuffer; Assert.IsNotNull(awaitable.Buffer.Array); Assert.AreEqual(awaitable.Buffer.Array.Length, 0); Assert.AreEqual(awaitable.Buffer.Offset, 0); Assert.AreEqual(awaitable.Buffer.Count, 0); // Assign a valid buffer. var data = new byte[32]; var buffer = new ArraySegment<byte>(data, 8, 16); awaitable.Buffer = buffer; Assert.AreSame(awaitable.Buffer.Array, data); Assert.AreEqual(awaitable.Buffer.Offset, buffer.Offset); Assert.AreEqual(awaitable.Buffer.Count, buffer.Count); // Clear awaitable. awaitable.Clear(); Assert.IsNotNull(awaitable.Buffer.Array); Assert.AreEqual(awaitable.Buffer.Array.Length, 0); Assert.AreEqual(awaitable.Buffer.Offset, 0); Assert.AreEqual(awaitable.Buffer.Count, 0); }
public async Task ReceiveAsyncNew() { Receiving = true; // Reusable SocketAsyncEventArgs and awaitable wrapper var args = new SocketAsyncEventArgs(); var buffer = BufferManager.DefaultManager.CheckOut(); args.SetBuffer(buffer, 0, buffer.Length); var awaitable = new SocketAwaitable(args); // Do processing, continually receiving from the socket while (Sock!=null) { try { if (!Sock.Connected) { break; } await Sock.ReceiveAsync(awaitable); int bytesRead = args.BytesTransferred; if (bytesRead <= 0) break; DataEventArgs data = new DataEventArgs(buffer, bytesRead); this.onDataReceived(this, data); } catch (SocketException ex) { break; } //catch (NullReferenceException ex) //{ // break; //} } Receiving = false; BufferManager.DefaultManager.CheckIn(buffer); Disconnect(); }
public async Task<byte[]> ReadBytesAsync(int count) { using (var args = new SocketAsyncEventArgs()) { args.SetBuffer(new byte[count], 0, count); var awaitable = new SocketAwaitable(args); await this.socket.ReceiveAsync(awaitable); var receivedBytes = new Byte[args.BytesTransferred]; Buffer.BlockCopy(args.Buffer, 0, receivedBytes, 0, args.BytesTransferred); return receivedBytes; } }
public async Task TestCommonOperations() { // Listen. using (var listener = new Socket(SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.IPv6Any, 0)); listener.Listen(1); var acceptReceiveTask = Task.Run(async () => { // Accept. Socket accepted; using (var acceptAwaitable = new SocketAwaitable()) { Assert.IsNull(acceptAwaitable.AcceptSocket); var acceptResult = await listener.AcceptAsync(acceptAwaitable); Assert.AreEqual(acceptResult, SocketError.Success); Assert.IsNotNull(acceptAwaitable.AcceptSocket); accepted = acceptAwaitable.AcceptSocket; } // Receive. using (var receiveAwaitable = new SocketAwaitable()) { receiveAwaitable.Buffer = new ArraySegment<byte>(new byte[16], 2, 14); var receiveResult = await accepted.ReceiveAsync(receiveAwaitable); Assert.AreEqual(receiveResult, SocketError.Success); Assert.AreEqual(receiveAwaitable.Transferred.Count, 1); Assert.AreEqual(receiveAwaitable.Buffer.Array[receiveAwaitable.Buffer.Offset], 7); } }); // Connect. using (var client = new Socket(SocketType.Stream, ProtocolType.Tcp)) { using (var connectAwaitable = new SocketAwaitable()) { connectAwaitable.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, (listener.LocalEndPoint as IPEndPoint).Port); var connectResult = await client.ConnectAsync(connectAwaitable); Assert.AreEqual(connectResult, SocketError.Success); } await Task.Delay(500); // Send. using (var sendAwaitable = new SocketAwaitable()) { sendAwaitable.Buffer = new ArraySegment<byte>(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 }, 7, 1); var sendResult = await client.SendAsync(sendAwaitable); Assert.AreEqual(sendResult, SocketError.Success); } // Await accept/receive task. await acceptReceiveTask; Assert.AreEqual(acceptReceiveTask.Status, TaskStatus.RanToCompletion); } } }
public async Task TestAwaiterStatus() { using (var listener = new Socket(SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.IPv6Any, 0)); listener.Listen(1); var acceptTask = Task.Run(async () => { using (var awaitable = new SocketAwaitable()) { var awaiter = awaitable.GetAwaiter(); Assert.IsTrue(awaiter.IsCompleted); Assert.AreEqual(awaiter.GetResult(), SocketError.Success); var a = listener.AcceptAsync(awaitable); Assert.IsFalse(awaiter.IsCompleted); Assert.AreEqual(awaiter.GetResult(), SocketError.AlreadyInProgress); var result = await a; Assert.IsTrue(awaiter.IsCompleted); Assert.AreEqual(awaiter.GetResult(), result); } }); await Task.Delay(500); using (var client = new Socket(SocketType.Stream, ProtocolType.Tcp)) { using (var awaitable = new SocketAwaitable()) { awaitable.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, (listener.LocalEndPoint as IPEndPoint).Port); var awaiter = awaitable.GetAwaiter(); Assert.IsTrue(awaiter.IsCompleted); Assert.AreEqual(awaiter.GetResult(), SocketError.Success); var a = client.ConnectAsync(awaitable); Assert.IsFalse(awaiter.IsCompleted); Assert.AreEqual(awaiter.GetResult(), SocketError.AlreadyInProgress); var result = await a; Assert.IsTrue(awaiter.IsCompleted); Assert.AreEqual(awaiter.GetResult(), result); } } await acceptTask; } }
public void TestDisposing() { var awaitable = new SocketAwaitable(); Assert.IsFalse(awaitable.IsDisposed); awaitable.Dispose(); Assert.IsTrue(awaitable.IsDisposed); }
public async Task<bool> Flush() { try { if (_socket == null) return false; if (_tosend.IsEmpty) return false; byte[] data; while (_tosend.TryDequeue(out data)) { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.SetBuffer(data, 0, data.Length); var awaitable = new SocketAwaitable(args); awaitable.OnCompleted(() => { RaiseSent(awaitable.GetResult()); }); await _socket.SendAsync(awaitable); } return true; } catch (Exception ex) { RaiseError(ex); throw; } }
public static async Task<int> ReceiveAsync(this Socket s, byte[] buffer) { var args = new SocketAsyncEventArgs(); args.SetBuffer(buffer); var awaitable = new SocketAwaitable(args); int totalBytesRead = 0; while (true) { await s.ReceiveAsync(awaitable); int bytesRead = args.BytesTransferred; if (bytesRead <= 0) break; totalBytesRead = bytesRead; } return totalBytesRead; }
public void TestGettingAwaiter() { var awaitable = new SocketAwaitable(); var awaiter = awaitable.GetAwaiter(); Assert.IsTrue(awaiter.IsCompleted); Assert.AreEqual(awaiter.GetResult(), default(SocketError)); }
public static SocketAwaitable ReceiveAsync(Socket socket, SocketAwaitable awaitable) { awaitable.Reset(); if (!socket.ReceiveAsync(awaitable.m_eventArgs)) awaitable.m_wasCompleted = true; return awaitable; }
/// <summary> /// Sends an <see cref="ISnmpMessage"/> and handles the response from agent. /// </summary> /// <param name="request">The <see cref="ISnmpMessage"/>.</param> /// <param name="receiver">Agent.</param> /// <param name="udpSocket">The UDP <see cref="Socket"/> to use to send/receive.</param> /// <param name="registry">The user registry.</param> /// <returns></returns> public static async Task<ISnmpMessage> GetResponseAsync(this ISnmpMessage request, IPEndPoint receiver, UserRegistry registry, Socket udpSocket) { if (request == null) { throw new ArgumentNullException("request"); } if (udpSocket == null) { throw new ArgumentNullException("udpSocket"); } if (receiver == null) { throw new ArgumentNullException("receiver"); } if (registry == null) { throw new ArgumentNullException("registry"); } var requestCode = request.TypeCode(); if (requestCode == SnmpType.TrapV1Pdu || requestCode == SnmpType.TrapV2Pdu || requestCode == SnmpType.ReportPdu) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "not a request message: {0}", requestCode)); } var bytes = request.ToBytes(); #if CF int bufSize = 8192; #else var bufSize = udpSocket.ReceiveBufferSize; #endif var reply = new byte[bufSize]; // Whatever you change, try to keep the Send and the Receive close to each other. udpSocket.SendTo(bytes, receiver); int count; try { // IMPORTANT: follow http://blogs.msdn.com/b/pfxteam/archive/2011/12/15/10248293.aspx var args = new SocketAsyncEventArgs(); args.SetBuffer(reply, 0, bufSize); var awaitable = new SocketAwaitable(args); count = await SocketExtensions.ReceiveAsync(udpSocket, awaitable); } catch (SocketException ex) { // FIXME: If you use a Mono build without the fix for this issue (https://bugzilla.novell.com/show_bug.cgi?id=599488), please uncomment this code. /* if (SnmpMessageExtension.IsRunningOnMono && ex.ErrorCode == 10035) { throw TimeoutException.Create(receiver.Address, timeout); } // */ if (ex.ErrorCode == WSAETIMEDOUT) { throw TimeoutException.Create(receiver.Address, 0); } throw; } // Passing 'count' is not necessary because ParseMessages should ignore it, but it offer extra safety (and would avoid an issue if parsing >1 response). var response = MessageFactory.ParseMessages(reply, 0, count, registry)[0]; var responseCode = response.TypeCode(); if (responseCode == SnmpType.ResponsePdu || responseCode == SnmpType.ReportPdu) { var requestId = request.MessageId(); var responseId = response.MessageId(); if (responseId != requestId) { throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response sequence: expected {0}, received {1}", requestId, responseId), receiver.Address); } return response; } throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response type: {0}", responseCode), receiver.Address); }
public async Task WriteSync(IList<ArraySegment<byte>> buffers) { using (var args = new SocketAsyncEventArgs()) { args.BufferList = buffers; var awaitable = new SocketAwaitable(args); await this.socket.SendAsync(awaitable); if (args.SocketError != SocketError.Success) { this.isAlive = false; ThrowHelper.ThrowSocketWriteError(this.endpoint, args.SocketError); } } }
async Task<bool> Receive() { try { if (_socket == null) return false; SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.SetBuffer(new byte[cBufferSize], 0, cBufferSize); var awaitable = new SocketAwaitable(args); List<byte> message = new List<byte>(); int bytes; while ((bytes = await _socket.ReceiveAsync(awaitable)) > 0) { message.AddRange(args.Buffer.Take(bytes).ToList()); } RaiseReceived(message.ToArray()); return await Receive(); } catch (Exception ex) { RaiseError(ex); return false; } }
public void TestSocketFlags() { // Default value. var awaitable = new SocketAwaitable(); Assert.AreEqual(awaitable.SocketFlags, SocketFlags.None); // Assign value. awaitable.SocketFlags = SocketFlags.Broadcast; Assert.AreEqual(awaitable.SocketFlags, SocketFlags.Broadcast); // Clear awaitable. awaitable.Clear(); Assert.AreEqual(awaitable.SocketFlags, SocketFlags.None); }
public void TestRemoteEndPoint() { // Default value. var awaitable = new SocketAwaitable(); Assert.IsNull(awaitable.RemoteEndPoint); // Assign value. var endPoint = new IPEndPoint(IPAddress.Loopback, IPEndPoint.MaxPort); awaitable.RemoteEndPoint = endPoint; Assert.AreSame(awaitable.RemoteEndPoint, endPoint); // Clear awaitable. awaitable.Clear(); Assert.IsNull(awaitable.RemoteEndPoint); }