protected override IEnumerable <IRequest> ReadAvailableMessages(ITcpClient tcpClient) { var streamReader = streamReaderFactory(tcpClient.GetStream()); var msg = streamReader.ReadAvailable(); yield return(ClientMessage.Create(msg, tcpClient)); }
/// <summary> /// Initializes a new instance of the <see cref="TcpTransport"/> class. /// </summary> /// <param name="tcpClient">The TCP client.</param> /// <param name="envelopeSerializer">The envelope serializer.</param> /// <param name="serverCertificate">The server certificate.</param> /// <param name="clientCertificate">The client certificate.</param> /// <param name="hostName">Name of the host.</param> /// <param name="bufferSize">Size of the buffer.</param> /// <param name="traceWriter">The trace writer.</param> /// <param name="serverCertificateValidationCallback">The server certificate validation callback.</param> /// <param name="clientCertificateValidationCallback">The client certificate validation callback.</param> /// <param name="ignoreDeserializationErrors">if set to <c>true</c> the deserialization on received envelopes will be ignored; otherwise, any deserialization error will be throw to the caller.</param> /// <exception cref="System.ArgumentNullException"> /// tcpClient /// or /// envelopeSerializer /// </exception> private TcpTransport( ITcpClient tcpClient, IEnvelopeSerializer envelopeSerializer, X509Certificate2 serverCertificate, X509Certificate2 clientCertificate, string hostName, int bufferSize, ITraceWriter traceWriter, RemoteCertificateValidationCallback serverCertificateValidationCallback, RemoteCertificateValidationCallback clientCertificateValidationCallback, bool ignoreDeserializationErrors) { if (tcpClient == null) { throw new ArgumentNullException(nameof(tcpClient)); } if (envelopeSerializer == null) { throw new ArgumentNullException(nameof(envelopeSerializer)); } _tcpClient = tcpClient; _jsonBuffer = new JsonBuffer(bufferSize); _envelopeSerializer = envelopeSerializer; _hostName = hostName; _traceWriter = traceWriter; _ignoreDeserializationErrors = ignoreDeserializationErrors; _receiveSemaphore = new SemaphoreSlim(1); _sendSemaphore = new SemaphoreSlim(1); _serverCertificate = serverCertificate; _clientCertificate = clientCertificate; _serverCertificateValidationCallback = serverCertificateValidationCallback ?? ValidateServerCertificate; _clientCertificateValidationCallback = clientCertificateValidationCallback ?? ValidateClientCertificate; }
public static async Task SendData(byte[] data, ITcpClient tcpClient, int sendTimeout) { using (var writeCts = new CancellationTokenSource(TimeSpan.FromMilliseconds(sendTimeout))) { try { if (tcpClient.Connected() && tcpClient.IsValidNetStream() && tcpClient.CanWrite() ) { await tcpClient.SendData(data, writeCts.Token); } else { throw new Exception("Network stream to send data is not initialized or it's busy. You should create a tcp connection first with SocketClient constructor and check that no errors appear."); } //TODO: change exception type } catch (OperationCanceledException) { throw new OperationCanceledException("Timeout of " + sendTimeout + " trying to send the data."); } } }
private void Connect(ITcpClient socket, AmqpTcpEndpoint endpoint, int timeout) { IAsyncResult ar = null; try { ar = socket.BeginConnect(endpoint.HostName, endpoint.Port, null, null); if (!ar.AsyncWaitHandle.WaitOne(timeout, false)) { socket.Close(); throw new TimeoutException("Connection to " + endpoint + " timed out"); } socket.EndConnect(ar); } catch (ArgumentException e) { throw new ConnectFailureException("Connection failed", e); } catch (SocketException e) { throw new ConnectFailureException("Connection failed", e); } finally { if (ar != null) { ar.AsyncWaitHandle.Close(); } } }
private TcpTransport(ITcpClient tcpClient, IEnvelopeSerializer envelopeSerializer, X509Certificate2 serverCertificate, X509Certificate2 clientCertificate, string hostName, int bufferSize, ITraceWriter traceWriter) { if (tcpClient == null) { throw new ArgumentNullException("tcpClient"); } _tcpClient = tcpClient; _buffer = new byte[bufferSize]; _bufferCurPos = 0; if (envelopeSerializer == null) { throw new ArgumentNullException("envelopeSerializer"); } _envelopeSerializer = envelopeSerializer; _hostName = hostName; _traceWriter = traceWriter; _receiveSemaphore = new SemaphoreSlim(1); _sendSemaphore = new SemaphoreSlim(1); _serverCertificate = serverCertificate; _clientCertificate = clientCertificate; }
private async Task AcceptTcpClientsAsync(ITcpListener tcpListener) { ExceptionDispatchInfo exceptionDispatchInfo = default; bool errorOcurred = false; while (!Disconnecting && !errorOcurred) { ITcpClient tcpClient = await DoAcceptTcpClientAsync(tcpListener).ConfigureAwait(false); AddClient(_tcpClients, tcpClient); async Task ClientReceiveAsync() { try { await TcpReceiver.ReceiveAsync(tcpClient).ConfigureAwait(false); } catch (Exception e) { errorOcurred = true; exceptionDispatchInfo = ExceptionDispatchInfo.Capture(e); tcpListener.Stop(); } } Task task = Task.Run(ClientReceiveAsync); } if (exceptionDispatchInfo != null) { throw new TcpIpAcceptClientsFailedException(exceptionDispatchInfo.SourceException); } }
private void AddClient(IDictionary <string, ITcpClient> tcpClients, ITcpClient client) { string tcpClientKey = Guid.NewGuid().ToString(); tcpClients.Add(tcpClientKey, client); OnClientAdded(tcpClientKey, client); }
public TcpResponseMessage(ITcpClient client, HttpRequestMessage request, Uri requestUri, TcpClientMessageHandler handler) { _requestUri = requestUri; _handler = handler; _client = client; RequestMessage = request; }
/// <summary> /// Read client data async. /// </summary> private async Task ReadDataAsync() { using (ITcpClient client = this.TcpClient) { try { while (client.Connected && this.TokenSource.IsCancellationRequested == false) { byte[] buffer = new byte[1024]; int size = await this.Stream.ReadAsync(buffer, 0, buffer.Length, TokenSource.Token); if (size == 0) { this.Disconnect(); return; } this.DataReceived?.Invoke(this, new DataReceivedEventArgs(size, buffer)); } this.Disconnect(); } catch { this.Disconnect(); } } }
private void ReturnClient(ITcpClient client) { try { if (statusCode == 200 && client.Connected && GetResponseHeader("Connection") != "close" && string.IsNullOrEmpty(_error)) { lock (connections) { List <ITcpClient> clients = null; if (!connections.TryGetValue(connectionKey, out clients)) { clients = new List <ITcpClient>(); connections[connectionKey] = clients; } clients.Add(client); } } else { // dispose client.Close(); } } catch { } }
protected void AsyncSendCallback(IAsyncResult ar) { try { ITcpClient tcpClient = (ITcpClient)ar.AsyncState; tcpClient.Socket.EndSend(ar); lock (m_locker) { if (m_sendedCommand != null) { for (int i = m_commandList.Count - 1; i >= 0; i--) { if (m_sendedCommand.Equals(m_commandList[i])) { m_commandList.RemoveAt(i); } } } } } catch (Exception ex) { SendErrorProcess(ex); } }
/// <summary> /// Connects the specified end point. /// </summary> /// <param name="endPoint">The end point.</param> /// <param name="bufferSize">Size of the buffer.</param> /// <param name="clientStreamFactory">The client stream factory.</param> /// <returns> /// Network Stream instance /// </returns> public NetworkStream Connect(AddressEndPoint endPoint, int bufferSize, IClientStreamFactory clientStreamFactory) { DoDisposeCheck(); if (endPoint == null) { ThrowHelper.ThrowArgumentNullException("endPoint"); } if (bufferSize < 0) { ThrowHelper.ThrowArgumentOutOfRangeException("bufferSize"); } if (clientStreamFactory == null) { ThrowHelper.ThrowArgumentNullException("clientStreamFactory"); } ITcpClient client = mNetworkFactory.CreateTcpClient(); client.Connect(endPoint); // ez dobhat kivételt client.Client.SendBufferSize = bufferSize; client.Client.ReceiveBufferSize = bufferSize; client.Client.SendTimeout = Timeout.Infinite; client.Client.ReceiveTimeout = Timeout.Infinite; client.Client.SetKeepAliveValues(true, DefaultSocketKeepAliveTime, DefaultSocketKeepAliveTimeInterval); client.Client.NoDelay = this.NoDelay; if (LOGGER.IsDebugEnabled) { LOGGER.Debug(string.Format("SYNAPSE_NETWORK_MANAGER, create client network stream for connection. Factory type: '{0}'. Connection remote endpoint: '{1}'", clientStreamFactory.GetType().FullName, endPoint.ToString())); } return(clientStreamFactory.CreateNetworkStream(client)); }
private static void SetupSuccessfulConnectionExpectations(ITcpClient tcpClient, INetworkStream stream, bool withPassword = true) { // client not connected tcpClient.Expect(x => x.Client).PropertyBehavior(); // setup connect expectations var asyncResult = MockRepository.GenerateStub <IAsyncResult>(); tcpClient.Expect(x => x.BeginConnect("server", 10000, null, null)).Return(asyncResult); asyncResult.Stub(x => x.AsyncWaitHandle).Return(new EventWaitHandle(true, EventResetMode.ManualReset)); tcpClient.Expect(x => x.EndConnect(asyncResult)).Do(new Action <IAsyncResult>(ar => { // setup Connected property expectations tcpClient.Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); tcpClient.Expect(x => x.Connected).Return(true).Repeat.AtLeastOnce(); })); tcpClient.Expect(x => x.GetStream()).Return(stream); if (withPassword) { // setup SendCommand() expectation stream.Expect(x => x.BeginWrite(null, 0, 0, null, null)).IgnoreArguments().Do( new Func <byte[], int, int, AsyncCallback, object, IAsyncResult>(TestUtilities.DoBeginWrite)).Repeat.AtLeastOnce(); } }
/// <summary> /// Initializes a new instance of the <see cref="TcpTransport"/> class. /// </summary> /// <param name="tcpClient">The TCP client.</param> /// <param name="envelopeSerializer">The envelope serializer.</param> /// <param name="serverCertificate">The server certificate.</param> /// <param name="clientCertificate">The client certificate.</param> /// <param name="hostName">Name of the host.</param> /// <param name="bufferSize">Size of the buffer.</param> /// <param name="maxBufferSize">Max size of the buffer.</param> /// <param name="arrayPool">The array pool instance, to allow reusing the created buffers.</param> /// <param name="traceWriter">The trace writer.</param> /// <param name="serverCertificateValidationCallback">The server certificate validation callback.</param> /// <param name="clientCertificateValidationCallback">The client certificate validation callback.</param> /// <exception cref="System.ArgumentNullException"> /// tcpClient /// or /// envelopeSerializer /// </exception> private TcpTransport( ITcpClient tcpClient, IEnvelopeSerializer envelopeSerializer, X509Certificate2 serverCertificate, X509Certificate2 clientCertificate, string hostName, int bufferSize, int maxBufferSize, ArrayPool <byte> arrayPool, ITraceWriter traceWriter, RemoteCertificateValidationCallback serverCertificateValidationCallback, RemoteCertificateValidationCallback clientCertificateValidationCallback) { _tcpClient = tcpClient ?? throw new ArgumentNullException(nameof(tcpClient)); _envelopeSerializer = envelopeSerializer ?? throw new ArgumentNullException(nameof(envelopeSerializer)); _serverCertificate = serverCertificate; _clientCertificate = clientCertificate; _hostName = hostName; _arrayPool = arrayPool ?? ArrayPool <byte> .Shared; _traceWriter = traceWriter; _serverCertificateValidationCallback = serverCertificateValidationCallback ?? ValidateServerCertificate; _clientCertificateValidationCallback = clientCertificateValidationCallback ?? ValidateClientCertificate; _jsonBuffer = new JsonBuffer(bufferSize, maxBufferSize, _arrayPool); _optionsSemaphore = new SemaphoreSlim(1); }
private void ConnectOrFail(ITcpClient socket, AmqpTcpEndpoint endpoint, TimeSpan timeout) { try { socket.ConnectAsync(endpoint.HostName, endpoint.Port) .TimeoutAfter(timeout) .ConfigureAwait(false) // this ensures exceptions aren't wrapped in an AggregateException .GetAwaiter() .GetResult(); } catch (ArgumentException e) { throw new ConnectFailureException("Connection failed", e); } catch (SocketException e) { throw new ConnectFailureException("Connection failed", e); } catch (NotSupportedException e) { throw new ConnectFailureException("Connection failed", e); } catch (TimeoutException e) { throw new ConnectFailureException("Connection failed", e); } }
public void RequestToGetTempNickNameTest_ConnectedStatus_NTR() { //Arrange string command = "NICK"; ITcpClient mockClient = Substitute.For <ITcpClient>(); mockClient.IsConnected().Returns(true); Client clientObj = new Client(mockClient); byte[] buffWithMessage = Encoding.UTF8.GetBytes(command); int length = buffWithMessage.Length; byte[] buffWithLength = BitConverter.GetBytes(length); //Act clientObj.RequestToGetTempNickName(); //Assert mockClient.Received(1).Write(Arg.Is <byte[]>(x => command == System.Text.Encoding.UTF8.GetString(x)), 0, length); mockClient.Received(1).Write(Arg.Is <byte[]>(x => length == BitConverter.ToInt32(x, 0)), 0, buffWithLength.Length); }
/// <summary> /// The function starts the the communication /// between the WEB and the server /// </summary> private void Start() { if (!Connected) { return; } Task task = new Task(() => { while (true) { try { string strMessage = m_client.Read(); if (strMessage == null) { connected = false; m_client = null; break; } MessageArrived?.Invoke(this, new CommandMessageEventArgs { Message = CommandMessage.FromJSONString(strMessage) }); } catch (IOException ex) { connected = false; m_client = null; break; } } }); task.Start(); }
public OpenConnection(SocksAddress address, ITcpClient client) { Address = address; Client = client; Timeout = InfiniteTimespan; MaxUsageCount = -1; }
public async Task ReceiveAsync(ITcpClient client) { try { ThrowIf.ArgumentIsNull(client, nameof(client)); byte[] buffer = new byte[BufferLength]; INetworkStream networkStream = default; try { networkStream = client.GetStream(); } catch (Exception exception) { if (!Disconnecting) { throw new TcpIpGetStreamFailedException(exception); } } StreamBufferReader2 streamBufferReader = StreamBufferReader2.Create(Identifier, Encoding.ASCII, Convert.ToByte(EndOfLine), SynchronizationContext, OnDataItemReceived); await ReceiveAsync(networkStream, streamBufferReader, buffer).ConfigureAwait(false); } catch (Exception exception) { if (!Disconnecting) { throw new TcpIpReceiveFailedException(exception); } } }
private async Task <IReadOnlyList <IMailReference> > TrySendToMx( string target, IReadOnlyList <IMailReference> mails, int port, CancellationToken token) { _log.Verbose($"Looking up information for MX {target}"); IPAddress targetIp = await _dns.QueryIp(target, token); if (targetIp == null) { _log.Warning($"Failed to resolve A or AAAA record for MX record {target}"); return(mails); } using (ITcpClient mxClient = _tcp.GetClient()) { _log.Information($"Connecting to MX {target} at {targetIp} on port {port}"); await mxClient.ConnectAsync(targetIp, port); using (Stream mxStream = mxClient.GetStream()) { mails = await TrySendMailsToStream(target, mails, mxStream, token); } } return(mails); }
private int ReadChunk(ITcpClient stream) { // read to the end of the line var line = ReadLine(stream); int count = 0; try { count = int.Parse(line, System.Globalization.NumberStyles.HexNumber); } catch { Error("Failed to decoded chunked response, line:" + line, Net.NetworkFailure.BadServerResponse); return(-1); } if (count == 0) { // read trailers ReadLine(stream); return(0); } //Debug.Log("Reading: " + count); var buffer = Read(stream, count); AddData(buffer); ReadLine(stream); // should have a CRLF after the buffer return(buffer.Length); }
//Prgramstart //run the connection----------------------------------------------------- public void Run() { string folderName = "messages"; if (!Directory.Exists(folderName)) { Directory.CreateDirectory(folderName); } running = true; listener.Start(); while (running) { Console.WriteLine("Waiting for connection..."); System.Net.Sockets.TcpClient client = GetClient(); //Connection with client myTcpClient = new TcpClient(client); Console.WriteLine("Client connected"); Thread objMyThread = new Thread(HandleClient); //hanlde function objMyThread.Start(); myTcpClient.End(); } running = false; listener.Stop(); }
private byte[] Read(ITcpClient stream, int count) { var buffer = new byte[count]; var read = 0; var timeout = System.DateTime.Now + _span; while (read < count) { var r = stream.Read(buffer, read, count - read); if (r < 0) { throw new System.IO.IOException("Read Failed"); } else if (r == 0) { if (System.DateTime.Now > timeout) { throw new System.IO.IOException("Read Timed out"); } System.Threading.Thread.Sleep(System.TimeSpan.FromMilliseconds(1)); } else { timeout = System.DateTime.Now + _span; read += r; } } return(buffer); }
//the function send the command to the service to get the data(status and photos number) public void sendCommand() { if (m_client != null) { //check if the client connect if (m_client.Connect()) { m_client.Send(new CommandRecievedEventArgs((int)CommandEnum.GetConfigCommand, null, null).ToJson()); } else { initialize(); } } else { try { m_client = TcpClientChannel.ClientInstance; isDelete = false; m_client.DataReceived += GetMessageFromClient; sendCommand(); } catch { } } }
internal static void Connect(Connection connection, ITcpClient tcpClient, INetworkStream stream) { SetupSuccessfulConnectionExpectations(tcpClient, stream); // set to 5 minutes so the update loop never gets a chance to fire connection.ReceiveLoopTime = 300000; connection.Connect("server", 10000, "password"); }
private string ReadLine(ITcpClient s) { var data = new List <byte>(64); var buffer = new byte[1]; while (true) { int r = s.Read(buffer, 0, 1); if (r == 0) { Thread.Sleep(10); continue; } byte b = buffer[0]; if (b == 10) // LF { break; } else if (b != 13) // CR { data.Add(b); } } return(Encoding.GetString(data.ToArray())); }
/// <summary> /// Constructor for incoming connections from clients /// </summary> /// <param name="client"></param> internal Connection(ITcpClient client, SslSettings sslSettings) : this(sslSettings) { // set random ID and connection direction ID = Guid.NewGuid().ToString().Substring(0, 8); IsClient = false; _tcpClient = client; _networkStream = _tcpClient.GetStream(); _networkStream.AuthenticateAsServer(); // create session ID provider - IDs are ODD for server-side initiated sessions _sessionIdProvider = new IdProvider(1, 2); // create and start frame decoder _streamDecoderTask = _decodeStreamAsync(_networkStream, _cts.Token); // block until the connection is active or it timesout var index = WaitHandle.WaitAny(new[] { _connectionOpen, _connectionError }, 2000); switch (index) { case 0: return; case 1: throw new ConnectionException(); case WaitHandle.WaitTimeout: throw new ConnectionTimeoutException(); default: throw new Exception(); } }
public async void Handle(ITcpClient client) { using (client) { _logger.Debug($"Tcp client connected: {client}, total clients: {CountTotalClients()}"); Interlocked.Increment(ref _concurrentTcpSessionCount); try { await Impl(client); } catch (TcpException ex) { _logger.Warn(ex.Message); } catch (Exception ex) { _logger.Error(ex); } finally { Interlocked.Decrement(ref _concurrentTcpSessionCount); // Logging _logger.Debug( $"Tcp client disconnected: {client}, total clients: {CountTotalClients()}" ); } } }
private bool WriteHeaders(ITcpClient stream) { // add the host header _requestHeaders["Host"] = _uri.Host; // support gzip if (OnDataCallback == null) { _requestHeaders["Accept-Encoding"] = "gzip"; } // this user agent _requestHeaders["User-Agent"] = "Sparx/1.0"; var sb = new System.Text.StringBuilder(); sb.AppendFormat("{0} {1} HTTP/1.1\r\n", _method, Proxy == null ? _uri.PathAndQuery : _uri.ToString()); foreach (var header in _requestHeaders) { sb.AppendFormat("{0}:{1}\r\n", header.Key, header.Value); } sb.Append("\r\n"); var buffer = System.Text.Encoding.UTF8.GetBytes(sb.ToString()); stream.Write(buffer, 0, buffer.Length); return(true); }
async Task Impl(ITcpClient client) { using (client) using (var networkActivityWatchDog = _tcpWatchDog.Watch(client)) { ApplyTcpSettings(client, _tcpSettings); Stream stream = client.GetStream(); // Wrap with SSL, if required. var t = await _sslService.WrapSslAsync(client, stream); if (t != null) { stream = t; } // Get the raw tcp stream. // For better exception handling and tracking of idle session, // we wrap it with our custom TcpStream. stream = (Stream) new TcpExceptionStreamDecorator( new WatchDogStreamDecorator(stream, networkActivityWatchDog)); // Create a TCP session and execute it var session = _tcpSessionFactory.Create(client, stream); try { await session.ExecuteAsync(); } finally { _tcpSessionFactory.Destroy(session); } } }
private ITcpClientFactory CreateClientFactory() { var tcpClientFactory = MockRepository.GenerateStub<ITcpClientFactory>(); _tcpClient = MockRepository.GenerateMock<ITcpClient>(); _stream = MockRepository.GenerateMock<INetworkStream>(); tcpClientFactory.Stub(x => x.Create()).Return(_tcpClient); return tcpClientFactory; }
public WebsocketClient(Uri url, ITcpClient tcpClient) { _url = url; _tcpClient = tcpClient; if (!_url.Scheme.Equals("ws") && !_url.Scheme.Equals("wss")) throw new ArgumentException("Unsupported scheme: " + _url.Scheme); }
public IscpStream(string hostName, ushort port, UnitType unitType, ITcpClient tcpClient = null) { _hostName = hostName; _port = port; _unitType = unitType; _tcpClient = tcpClient ?? new TcpClient(); _outbound = new Subject<IPacket>(); _inbound = new Subject<IPacket>(); }
public Client(string host, int port, bool useSsl, ITcpClient client = null) { Logger.DebugFormat("Enter Client({0}, {1}, {2})", host, port, useSsl); TcpClient = client ?? new TcpClientWrapper(); Host = host; Port = port; UseSsl = useSsl; Logger.DebugFormat("Leave Client"); }
public IoClientInterface(ILoggers logger, ITcpClient tcpClient, char endOfMessageChar = EndofMessageChar) { _logger = logger; _tcpClient = tcpClient; Initialise(); _endOfMessage = endOfMessageChar; _heartbeatPeriod = TimeSpan.FromSeconds(HeartbeatPeriod); _heartbeatTimer = new Timer(HeartbeatTimerElapsed,null, 0, (int)_heartbeatPeriod.TotalMilliseconds); //_heartbeatTimer.Elapsed += HeartbeatTimerElapsed; //_heartbeatTimer.Interval = _heartbeatPeriod.TotalMilliseconds; //_heartbeatTimer.Start(); }
public SocketFrameHandler(AmqpTcpEndpoint endpoint, Func<AddressFamily, ITcpClient> socketFactory, int connectionTimeout, int readTimeout, int writeTimeout) { Endpoint = endpoint; m_socket = null; if (Socket.OSSupportsIPv6) { try { m_socket = socketFactory(AddressFamily.InterNetworkV6); Connect(m_socket, endpoint, connectionTimeout); } catch (ConnectFailureException) // could not connect using IPv6 { m_socket = null; } // Mono might raise a SocketException when using IPv4 addresses on // an OS that supports IPv6 catch (SocketException) { m_socket = null; } } if (m_socket == null) { m_socket = socketFactory(AddressFamily.InterNetwork); Connect(m_socket, endpoint, connectionTimeout); } Stream netstream = m_socket.GetStream(); netstream.ReadTimeout = readTimeout; netstream.WriteTimeout = writeTimeout; if (endpoint.Ssl.Enabled) { try { netstream = SslHelper.TcpUpgrade(netstream, endpoint.Ssl); } catch (Exception) { Close(); throw; } } m_reader = new NetworkBinaryReader(new BufferedStream(netstream)); m_writer = new NetworkBinaryWriter(new BufferedStream(netstream)); m_writeableStateTimeout = writeTimeout; }
public WebSocketClient(Uri location, ILogger logger = null, ITcpClient tcpClient = null) { if (location == null) throw new ArgumentNullException("location"); OnOpen = () => { }; OnClose = () => { }; OnMessage = x => { }; OnBinary = x => { }; OnPing = x => SendPongAsync(x); OnPong = x => { }; OnError = x => { }; _location = location; _logger = logger ?? new DebuggerLogger(); _handshakeFinished = new ManualResetEventSlim(); _responseParser = new RegexResponseParser(); _handler = new Hybi13Handler(_logger, m => OnMessage(m), () => OnClose(), m => OnBinary(m), x => OnPing(x), x => OnPong(x), x => OnError(x)); _tcpClient = tcpClient ?? new TcpClient(location.DnsSafeHost, location.Port); }
private void Connect(ITcpClient socket, AmqpTcpEndpoint endpoint, int timeout) { try { socket.ConnectAsync(endpoint.HostName, endpoint.Port) .TimeoutAfter(timeout) .ConfigureAwait(false) .GetAwaiter()//this ensures exceptions aren't wrapped in an AggregateException .GetResult(); } catch (ArgumentException e) { throw new ConnectFailureException("Connection failed", e); } catch (SocketException e) { throw new ConnectFailureException("Connection failed", e); } catch (NotSupportedException e) { throw new ConnectFailureException("Connection failed", e); } catch (TimeoutException e) { throw new ConnectFailureException("Connection failed", e); } }
public EcosModel(ITcpClient tcpClientInstance) { if (tcpClientInstance == null) throw new ArgumentNullException("tcpClientInstance"); tcpClient = tcpClientInstance; tcpClient.Connected += tcpClient_Connected; tcpClient.ConnectFailed += tcpClient_ConnectFailed; tcpClient.Disconnected += tcpClient_Disconnected; tcpClient.ServerDisconnected += tcpClient_ServerDisconnected; tcpClient.Received += tcpClient_DataReceived; IsConnected = tcpClient.IsConnected; managers.Add(ecosManager = new EcosManager()); managers.Add(locomotiveManager = new LocomotiveManager()); managers.Add(accessoryManager = new AccessoryManager()); managers.Add(feedbackManager = new FeedbackManager()); //managers.Add(snifferManager = new SnifferManager()); //managers.Add(boosterManager = new BoosterManager()); // in future //managers.Add(deviceManager = new DeviceManager()); // in future foreach (Manager manager in managers) manager.CommandError += (s, e) => { if (CommandError != null) CommandError(s, e); }; ecosManager.PropertyChanged += (s, e) => { if (e.PropertyName == "ApplicationVersion" && isAutoPopulateLocomotivesUserImages) // app version received; LocomotiveImagesManager.PopulateUserImagesAsync(ipAddress, UserLocomotiveImagesUrl); }; }
public void Close() { _tcpClient.Close(); _tcpClient = null; }
private static void SetupSuccessfulConnectionExpectations(ITcpClient tcpClient, INetworkStream stream, bool withPassword = true) { // client not connected tcpClient.Expect(x => x.Client).Return(null); // setup connect expectations var asyncResult = MockRepository.GenerateStub<IAsyncResult>(); tcpClient.Expect(x => x.BeginConnect("server", 10000, null, null)).Return(asyncResult); asyncResult.Stub(x => x.AsyncWaitHandle).Return(new EventWaitHandle(true, EventResetMode.ManualReset)); tcpClient.Expect(x => x.EndConnect(asyncResult)); tcpClient.Expect(x => x.GetStream()).Return(stream); // setup Connected property expectations tcpClient.Expect(x => x.Client).Return(new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)).Repeat.AtLeastOnce(); tcpClient.Expect(x => x.Connected).Return(true).Repeat.AtLeastOnce(); if (withPassword) { // setup SendCommand() expectation var buffer = Encoding.ASCII.GetBytes("auth password\n"); stream.Expect(x => x.Write(buffer, 0, buffer.Length)); } }
/// <summary> /// Initializes a new instance of the <see cref="TcpTransport"/> class. /// This constructor is used by the <see cref="TcpTransportListener"/> class. /// </summary> /// <param name="tcpClient">The TCP client.</param> /// <param name="envelopeSerializer">The envelope serializer.</param> /// <param name="serverCertificate">The server certificate.</param> /// <param name="bufferSize">Size of the buffer.</param> /// <param name="traceWriter">The trace writer.</param> internal TcpTransport(ITcpClient tcpClient, IEnvelopeSerializer envelopeSerializer, X509Certificate2 serverCertificate, int bufferSize = DEFAULT_BUFFER_SIZE, ITraceWriter traceWriter = null) : this(tcpClient, envelopeSerializer, serverCertificate, null, null, bufferSize, traceWriter) { }
public ServerServicesProvider(ITcpClient tcpClient, IDnsResolver dnsResolver, IPinger pinger) { TcpClient = tcpClient; DnsResolver = dnsResolver; Pinger = pinger; }
public ConnectionEstablishedEventArgs(ITcpClient client) { Client = client; }
/// <summary> /// Initializes a new instance of the Connection class. /// </summary> internal Connection(ITcpClientFactory tcpClientFactory) { ConnectTimeout = DefaultTimeoutLength; _tcpClientFactory = tcpClientFactory; _tcpClient = CreateClient(); _internalBuffer = new byte[InternalBufferSize]; _readBuffer = new StringBuilder(); _timer = new Timer(DefaultSocketTimerLength); _timer.Elapsed += SocketTimerElapsed; }
/// <summary> /// Initializes a new instance of the <see cref="TcpTransport"/> class. /// </summary> /// <param name="tcpClient">The TCP client.</param> /// <param name="envelopeSerializer">The envelope serializer.</param> /// <param name="hostName">Name of the host.</param> /// <param name="bufferSize">Size of the buffer.</param> /// <param name="traceWriter">The trace writer.</param> public TcpTransport(ITcpClient tcpClient, IEnvelopeSerializer envelopeSerializer, string hostName, X509Certificate2 clientCertificate = null, int bufferSize = DEFAULT_BUFFER_SIZE, ITraceWriter traceWriter = null) : this(tcpClient, envelopeSerializer, null, clientCertificate, hostName, bufferSize, traceWriter) { }
/// <summary> /// Connect to a Folding@Home client server. /// </summary> /// <param name="host">Hostname or IP address.</param> /// <param name="port">TCP port number.</param> /// <param name="password">Server password.</param> /// <exception cref="InvalidOperationException">Connection is already connected.</exception> /// <exception cref="ArgumentNullException"><paramref name="host"/> or <paramref name="password"/> is null.</exception> /// <exception cref="TimeoutException">Connection attempt timed out.</exception> public void Connect(string host, int port, string password) { // check connection status, callers should make sure no connection exists first if (Connected) throw new InvalidOperationException("Client is already connected."); if (host == null) throw new ArgumentNullException("host"); if (password == null) throw new ArgumentNullException("password"); if (_tcpClient != null) { _tcpClient.Dispose(); } _tcpClient = CreateClient(); IAsyncResult ar = _tcpClient.BeginConnect(host, port, null, null); try { if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(ConnectTimeout), false)) { _tcpClient.Close(); throw new TimeoutException("Client connection has timed out."); } _tcpClient.EndConnect(ar); _stream = _tcpClient.GetStream(); if (password.Length != 0) { // send authentication SendCommand("auth " + password); } if (Connected) { // send connected event OnConnectedChanged(new ConnectedChangedEventArgs(true)); // maybe use Connected property? // send status message OnStatusMessage(new StatusMessageEventArgs(String.Format(CultureInfo.CurrentCulture, "Connected to {0}:{1}", host, port), TraceLevel.Info)); // start listening for messages // from the network stream _timer.Start(); } } finally { ar.AsyncWaitHandle.Close(); } }
/// <summary> /// Connect to a Folding@Home client server. /// </summary> /// <param name="host">Hostname or IP address.</param> /// <param name="port">TCP port number.</param> /// <param name="password">Server password.</param> /// <exception cref="InvalidOperationException">Connection is already connected.</exception> /// <exception cref="ArgumentNullException"><paramref name="host"/> or <paramref name="password"/> is null.</exception> /// <exception cref="TimeoutException">Connection attempt timed out.</exception> public void Connect(string host, int port, string password) { // check connection status, callers should make sure no connection exists first if (Connected) throw new InvalidOperationException("Client is already connected."); if (host == null) throw new ArgumentNullException("host"); if (password == null) throw new ArgumentNullException("password"); if (_tcpClient != null) { _tcpClient.Dispose(); } _tcpClient = CreateClient(); IAsyncResult ar = _tcpClient.BeginConnect(host, port, null, null); try { if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(ConnectTimeout), false)) { _tcpClient.Close(); throw new TimeoutException("Client connection has timed out."); } _tcpClient.EndConnect(ar); _stream = _tcpClient.GetStream(); if (password.Length != 0) { // send authentication SendCommand("auth " + password); } if (Connected) { // send connected event OnConnectedChanged(new ConnectedChangedEventArgs(true)); // maybe use Connected property? // send status message OnStatusMessage(new StatusMessageEventArgs(String.Format(CultureInfo.CurrentCulture, "Connected to {0}:{1}", host, port), TraceLevel.Info)); // start listening for messages // from the network stream _timer.Start(); } } finally { /* * when running on Mono, if we time out connecting, * TcpClient.Close() (above) causes asynchronous access * (coming from BeginConnect-related path) to AsyncWaitHandle. * This opens a race window with closing the handle below. * * Unfortunate chain of events results in the following: Unhandled Exception: System.ObjectDisposedException: The object was used after being disposed. at System.Threading.WaitHandle.CheckDisposed () at System.Threading.EventWaitHandle.Set () at (wrapper remoting-invoke-with-check) System.Threading.EventWaitHandle:Set () at System.Net.Sockets.Socket+SocketAsyncResult.set_IsCompleted (Boolean value) at System.Net.Sockets.Socket+SocketAsyncResult.Complete () at System.Net.Sockets.Socket+SocketAsyncResult.Complete (System.Exception e) at System.Net.Sockets.Socket+Worker.Connect () at System.Net.Sockets.Socket+Worker.DispatcherCB (System.Net.Sockets.SocketAsyncResult sar) * As Mono's TcpClient.Close() signals AsyncWaitHandle, we can * just wait on it before proceeding. * * Note: we can't wait on the handle right after closing TcpClient * because closing the client may throw. * */ if (IsRunningOnMono) { ar.AsyncWaitHandle.WaitOne(); } ar.AsyncWaitHandle.Close(); } }
private static void SetupSuccessfulConnectionExpectations(ITcpClient tcpClient, INetworkStream stream, bool withPassword = true) { // client not connected tcpClient.Expect(x => x.Client).PropertyBehavior(); // setup connect expectations var asyncResult = MockRepository.GenerateStub<IAsyncResult>(); tcpClient.Expect(x => x.BeginConnect("server", 10000, null, null)).Return(asyncResult); asyncResult.Stub(x => x.AsyncWaitHandle).Return(new EventWaitHandle(true, EventResetMode.ManualReset)); tcpClient.Expect(x => x.EndConnect(asyncResult)).Do(new Action<IAsyncResult>(ar => { // setup Connected property expectations tcpClient.Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); tcpClient.Expect(x => x.Connected).Return(true).Repeat.AtLeastOnce(); })); tcpClient.Expect(x => x.GetStream()).Return(stream); if (withPassword) { // setup SendCommand() expectation stream.Expect(x => x.BeginWrite(null, 0, 0, null, null)).IgnoreArguments().Do( new Func<byte[], int, int, AsyncCallback, object, IAsyncResult>(TestUtilities.DoBeginWrite)).Repeat.AtLeastOnce(); } }
public EcosModel(ITcpClient tcpClientInstance) { if (tcpClientInstance == null) throw new ArgumentNullException("tcpClientInstance"); tcpClient = tcpClientInstance; tcpClient.Connected += tcpClient_Connected; tcpClient.ConnectFailed += tcpClient_ConnectFailed; tcpClient.Disconnected += tcpClient_Disconnected; tcpClient.ServerDisconnected += tcpClient_ServerDisconnected; tcpClient.Received += tcpClient_DataReceived; tcpClient.Log += tcpClient_Log; IsConnected = tcpClient.IsConnected; managers.Add(ecosManager = new EcosManager()); managers.Add(locomotiveManager = new LocomotiveManager()); managers.Add(accessoryManager = new AccessoryManager()); managers.Add(feedbackManager = new FeedbackManager()); //managers.Add(snifferManager = new SnifferManager()); //managers.Add(boosterManager = new BoosterManager()); // in future //managers.Add(deviceManager = new DeviceManager()); // in future foreach (Manager manager in managers) { manager.CommandError += manager_CommandError; manager.PropertyChanged += manager_PropertyChanged; } }
/// <summary> /// Initializes a new instance of the Connection class. /// </summary> internal Connection(ITcpClientFactory tcpClientFactory) { ConnectTimeout = DefaultTimeoutLength; _tcpClientFactory = tcpClientFactory; _lockedStream = new LockedResource<INetworkStream>(); _tcpClient = CreateClient(); _internalBuffer = new byte[InternalBufferSize]; _readBuffer = new StringBuilder(); }
internal static void Connect(Connection connection, ITcpClient tcpClient, INetworkStream stream) { SetupSuccessfulConnectionExpectations(tcpClient, stream); connection.Connect("server", 10000, "password"); }