public void TestConcurrentAccess() { int count = 20; // Initialize using a specific count. var pool = new SocketAwaitablePool(count); Assert.AreEqual(pool.Count, count); // Deplete the pool. Parallel.For(0, count, i => Assert.IsNotNull(pool.Take())); Assert.AreEqual(pool.Count, 0); // Force pool to initialize new awaitables. var newAwaitables = new SocketAwaitable[count]; Parallel.For(0, count, i => Assert.IsNotNull(newAwaitables[i] = pool.Take())); // Add new awaitables [back] to the pool. Parallel.For(0, count, i => pool.Add(newAwaitables[i])); Assert.AreEqual(pool.Count, count); // Add to, take from and iterate the pool in parallel. var addTask = Task.Run( () => Parallel.For(0, 1000000, i => pool.Add(new SocketAwaitable()))); var takeTask = Task.Run( () => Parallel.For(0, 1000000 + count, i => Assert.IsNotNull(pool.Take()))); var iterateTask = Task.Run( () => Parallel.ForEach(pool, e => Assert.IsNotNull(e))); Task.WaitAll(addTask, takeTask, iterateTask); }
private async Task ConnectAsync(EndPoint endPoint) { var result = SocketError.Fault; for (var i = 0; i < _socketConnectAttempts; i++) { if (_socket != null) { _socket.Close(); _socket = null; } _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { UseOnlyOverlappedIO = true, NoDelay = true, ReceiveTimeout = _receiveTimeout, SendTimeout = _sendTimeout, ReceiveBufferSize = _receiveBufferSize, SendBufferSize = _sendBufferSize }; var awaitable = _socketAwaitablePool.Take(); try { awaitable.RemoteEndPoint = endPoint; var socketAwaitable = _socket.ConnectAsync(awaitable); _lastActivity = DateTime.UtcNow; result = await socketAwaitable; if (result == SocketError.Success) { break; } } finally { awaitable.Clear(); _socketAwaitablePool.Add(awaitable); } } if (result != SocketError.Success) { if (_socket != null) { _socket.Close(); _socket = null; } throw new RiakException("Unable to connect to remote server: {0}:{1} error code {2}".Fmt(_endPoint.Host, _endPoint.Port, result)); } }
public void TestTakingAfterDispose() { var pool = new SocketAwaitablePool(); pool.Dispose(); pool.Take(); }
public async Task SendAsyncImmediatelly(byte[] packetBytes) { int totalBytesSent = 0; var socketAwaitable = socketAwaitablePool.Take(); var sendBuffer = bufferManager.GetBuffer(); var sendBufferMaxSize = sendBuffer.Count; try { while (totalBytesSent < packetBytes.Length) { socketAwaitable.Clear(); var writeCount = Math.Min(packetBytes.Length - totalBytesSent, sendBufferMaxSize); Buffer.BlockCopy(packetBytes, totalBytesSent, sendBuffer.Array, sendBuffer.Offset, writeCount); socketAwaitable.Buffer = new ArraySegment <byte>(sendBuffer.Array, sendBuffer.Offset, writeCount); var result = await Socket.SendAsync(socketAwaitable); if (result != SocketError.Success || socketAwaitable.Transferred.Count == 0) { if (Logger.IsDebugEnabled && result != SocketError.Success) { Logger.Debug("Socket did not succeed when sending a packet socketError[{0}] IP[{1}]", result, RemoteIP); } return; } totalBytesSent += socketAwaitable.Transferred.Count; } } // Ignore cases where we accidentally send to the socket after its been disposed catch (ObjectDisposedException) { } catch (Exception e) { Logger.Warn(e, "Unexpected exception in send IP[{0}]", RemoteIP); } finally { socketAwaitable.Clear(); socketAwaitablePool.Add(socketAwaitable); bufferManager.ReleaseBuffer(sendBuffer); } }
public async Task <string> AsyncConversation(string msgOut) { // Data buffer for incoming data. byte[] bytes = new byte[1024]; // Connect to a remote device. try { // Establish the remote endpoint for the socket. // This example uses port 11000 on the local computer. //IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); //IPAddress ipAddress; //IPAddress.TryParse("10.200.90.7", out ipAddress); IPEndPoint remoteEP = new IPEndPoint(oServer.IP, 17011); // Create a TCP/IP socket. Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Connect the socket to the remote endpoint. Catch any errors. try { Status = SocksStatus.TRYCONNECT; sender.Connect(remoteEP); Status = SocksStatus.CONNECTED; //RunOnUiThread(() => txtConsole.Text += String.Format("Socket connected to {0}\n", sender.RemoteEndPoint.ToString())); //Console.WriteLine("Socket connected to {0}", // sender.RemoteEndPoint.ToString()); // Encode the data string into a byte array. var awaitable = awaitables.Take(); awaitable.Buffer = new ArraySegment <byte>(Encoding.ASCII.GetBytes(msgOut)); while (true) { if (await sender.SendAsync(awaitable) != SocketError.Success) { throw(new Exception("Error lala")); // or log and throw an exception. } if (awaitable.Buffer.Count == awaitable.Transferred.Count) { break; // Break if all the data is sent. } // Set the buffer to send the remaining data. awaitable.Buffer = new ArraySegment <byte>( awaitable.Buffer.Array, awaitable.Buffer.Offset + awaitable.Transferred.Count, awaitable.Buffer.Count - awaitable.Transferred.Count); } awaitable.Clear(); // Receive the response from the remote device. string _result = ""; // Get a buffer from the pool. var buffer = buffers.GetBuffer(); while (true) { awaitable.Buffer = buffer; // Receive data from the client. var result = await sender.ReceiveAsync(awaitable); if (result != SocketError.Success) { // Something went wrong. // Check `result` and break the loop. break; } _result += Encoding.ASCII.GetString(buffer.ToArray <byte>(), 0, awaitable.Transferred.Count); // Received data is now in `awaitable.Transferred`. if (awaitable.Transferred.Count == 0) { // The client "gracefully" closed the connection. break; } } sender.Shutdown(SocketShutdown.Both); sender.Close(); Status = SocksStatus.OFFLINE; return(_result); } catch (ArgumentNullException ane) { Status = SocksStatus.ERROR; _ErrorMsg = string.Format("ArgumentNullException : {0}", ane.Message); throw (ane); //Console.WriteLine("ArgumentNullException : {0}", ane.ToString()); } catch (SocketException se) { Status = SocksStatus.ERROR; _ErrorMsg = string.Format("SocketException : {0}", se.Message); throw (se); //Console.WriteLine("SocketException : {0}", se.ToString()); } catch (Exception e) { Status = SocksStatus.ERROR; _ErrorMsg = string.Format("Unexpected exception : {0}", e.Message); throw (e); //Console.WriteLine("Unexpected exception : {0}", e.ToString()); } } catch (Exception e) { Status = SocksStatus.ERROR; _ErrorMsg = string.Format("General exception : {0}", e.Message); return(""); throw (e); //Console.WriteLine(e.ToString()); } }