public async Task<bool> IsPortReachable(string host, int port = 80, int msTimeout = 5000) { if (string.IsNullOrEmpty(host)) throw new ArgumentNullException("host"); return await Task.Run(() => { var clientDone = new ManualResetEvent(false); var reachable = false; var hostEntry = new DnsEndPoint(host, port); using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { var socketEventArg = new SocketAsyncEventArgs { RemoteEndPoint = hostEntry }; socketEventArg.Completed += (s, e) => { reachable = e.SocketError == SocketError.Success; clientDone.Set(); }; clientDone.Reset(); socket.ConnectAsync(socketEventArg); clientDone.WaitOne(msTimeout); return reachable; } }); }
public void Connect(string host, int port) { DnsEndPoint endPoint = new DnsEndPoint(host, port); SocketAsyncEventArgs asEventArg = new SocketAsyncEventArgs(); asEventArg.RemoteEndPoint = endPoint; _myEvent.Reset(); asEventArg.Completed += (object sender, SocketAsyncEventArgs arg) => { if (arg.SocketError == SocketError.Success) { Debug.WriteLine("Connect with Server"); Debug.WriteLine("Start to send SocketFlag"); m_host = host; m_port = port; byte[] socketFlag = new byte[1]; socketFlag[0] = (byte)m_protocolFlag; SendSocketFlag(socketFlag); Debug.WriteLine("SocketFlag has sent"); } else { Debug.WriteLine("Did not connect with Server... \nThe Reson is {0}",arg.SocketError.ToString()); } _myEvent.Set(); }; m_tcpClient.ConnectAsync(asEventArg); _myEvent.WaitOne(Timeout); }
/// <summary> /// Send data to the server /// </summary> /// <param name="data">The data to send</param> /// <remarks> This is an asynchronous call, with the result being passed to the callee /// through the ResponseReceived event</remarks> public void SendData(string data) { if (String.IsNullOrWhiteSpace(data)) { throw new ArgumentNullException("data"); } dataIn = data; SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs(); DnsEndPoint hostEntry = new DnsEndPoint(_serverName, _port); // Create a socket and connect to the server Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(SocketEventArg_Completed); socketEventArg.RemoteEndPoint = hostEntry; socketEventArg.UserToken = sock; try { sock.ConnectAsync(socketEventArg); } catch (SocketException ex) { throw new SocketException((int)ex.ErrorCode); } }
/// <summary> /// Initializes a new instance of the <see cref="SocketClient"/> class. /// </summary> /// <param name="host">The host.</param> /// <param name="port">The port.</param> internal SocketClient(string host, int port) { endPoint = new DnsEndPoint(host, port); socket = new Socket(AddressFamily.InterNetwork /* hostEndPoint.AddressFamily */, SocketType.Stream, ProtocolType.Tcp); }
public BinaryConnection_CommandEventTests() { _capturedEvents = new EventCapturer() .Capture<CommandStartedEvent>() .Capture<CommandSucceededEvent>() .Capture<CommandFailedEvent>(); _mockStreamFactory = new Mock<IStreamFactory>(); _endPoint = new DnsEndPoint("localhost", 27017); var serverId = new ServerId(new ClusterId(), _endPoint); _mockConnectionInitializer = new Mock<IConnectionInitializer>(); _mockConnectionInitializer.Setup(i => i.InitializeConnectionAsync(It.IsAny<IConnection>(), CancellationToken.None)) .Returns(() => Task.FromResult(new ConnectionDescription( new ConnectionId(serverId), new IsMasterResult(new BsonDocument()), new BuildInfoResult(new BsonDocument("version", "2.6.3"))))); _subject = new BinaryConnection( serverId: serverId, endPoint: _endPoint, settings: new ConnectionSettings(), streamFactory: _mockStreamFactory.Object, connectionInitializer: _mockConnectionInitializer.Object, eventSubscriber: _capturedEvents); _stream = new BlockingMemoryStream(); _mockStreamFactory.Setup(f => f.CreateStreamAsync(_endPoint, CancellationToken.None)) .Returns(Task.FromResult<Stream>(_stream)); _subject.OpenAsync(CancellationToken.None).Wait(); _capturedEvents.Clear(); _operationIdDisposer = EventContext.BeginOperation(); }
public bool TryConvertTo(Type type, string stringValue, out object converted) { if (type != typeof(DnsEndPoint)) { converted = null; return false; } int idx = stringValue.IndexOf(':'); if (idx == -1) { converted = null; return false; } string host = stringValue.Substring(0, idx); int port; if (!int.TryParse(stringValue.Substring(idx + 1), out port)) { converted = null; return false; } try { converted = new DnsEndPoint(host, port); return true; } catch (ArgumentException) { converted = null; return false; } }
public static Task<NameResolutionResult> ResolveHostNameAsync(DnsEndPoint dnsEndPoint) { var taskCompletionSource = new TaskCompletionSource<NameResolutionResult>(); DeviceNetworkInformation.ResolveHostNameAsync(dnsEndPoint, r => { var tcs = (TaskCompletionSource<NameResolutionResult>)r.AsyncState; switch (r.NetworkErrorCode) { case NetworkError.NameResolutionOperationAborted: tcs.TrySetCanceled(); break; case NetworkError.Success: tcs.TrySetResult(r); break; default: tcs.TrySetException(new NetworkException(r.NetworkErrorCode)); break; } }, taskCompletionSource); return taskCompletionSource.Task; }
public void ConnectTo(DnsEndPoint hostEntry) { _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); SocketError _lastError = SocketError.NotConnected; SocketAsyncEventArgs socketEventArgs = new SocketAsyncEventArgs(); socketEventArgs.RemoteEndPoint = hostEntry; socketEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e) { _lastError = e.SocketError; _End(); // Install read and write handler _socketReadEventArgs = new SocketAsyncEventArgs(); _socketReadEventArgs.RemoteEndPoint = _socket.RemoteEndPoint; _socketReadEventArgs.SetBuffer(new byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE); _socketReadEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(_AsyncCallComplete); _socketWriteEventArgs = new SocketAsyncEventArgs(); _socketWriteEventArgs.RemoteEndPoint = _socket.RemoteEndPoint; _socketWriteEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(_AsyncCallComplete); }); // async connect _Reset(); _socket.ConnectAsync(socketEventArgs); _BlockUI(); if (_lastError != SocketError.Success) { // connection failed throw new Exception(String.Format(LocalizedStrings.Get("Net_StreamSocket_ConnectFailed"), hostEntry, _lastError.ToString())); } }
/// <summary> /// Connect to the server /// </summary> /// <param name="ipAddress">IP address of the server</param> /// <param name="port">port to connect to</param> /// <returns></returns> public string Connect(string ipAddress, int port) { string result = string.Empty; bool finished = false; DnsEndPoint host = new DnsEndPoint(ipAddress, port); this.sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); SocketAsyncEventArgs socketEventArgs = new SocketAsyncEventArgs(); socketEventArgs.RemoteEndPoint = host; socketEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>( delegate (object s, SocketAsyncEventArgs e) { result = e.SocketError.ToString(); this.clientDone.Set(); finished = true; }); this.clientDone.Reset(); this.sock.ConnectAsync(socketEventArgs); this.clientDone.WaitOne(TCPIPconnectorClient.timeout); if (!finished) { result = "!error"; } return result; }
public BinaryConnectionTests() { _capturedEvents = new EventCapturer(); _mockStreamFactory = new Mock<IStreamFactory>(); _endPoint = new DnsEndPoint("localhost", 27017); var serverId = new ServerId(new ClusterId(), _endPoint); _mockConnectionInitializer = new Mock<IConnectionInitializer>(); _mockConnectionInitializer.Setup(i => i.InitializeConnection(It.IsAny<IConnection>(), CancellationToken.None)) .Returns(() => new ConnectionDescription( new ConnectionId(serverId), new IsMasterResult(new BsonDocument()), new BuildInfoResult(new BsonDocument("version", "2.6.3")))); _mockConnectionInitializer.Setup(i => i.InitializeConnectionAsync(It.IsAny<IConnection>(), CancellationToken.None)) .Returns(() => Task.FromResult(new ConnectionDescription( new ConnectionId(serverId), new IsMasterResult(new BsonDocument()), new BuildInfoResult(new BsonDocument("version", "2.6.3"))))); _subject = new BinaryConnection( serverId: serverId, endPoint: _endPoint, settings: new ConnectionSettings(), streamFactory: _mockStreamFactory.Object, connectionInitializer: _mockConnectionInitializer.Object, eventSubscriber: _capturedEvents); }
public void Setup() { _capturedEvents = new EventCapturer(); _streamFactory = Substitute.For<IStreamFactory>(); _endPoint = new DnsEndPoint("localhost", 27017); var serverId = new ServerId(new ClusterId(), _endPoint); _connectionInitializer = Substitute.For<IConnectionInitializer>(); _connectionInitializer.InitializeConnection(null, CancellationToken.None) .ReturnsForAnyArgs(new ConnectionDescription( new ConnectionId(serverId), new IsMasterResult(new BsonDocument()), new BuildInfoResult(new BsonDocument("version", "2.6.3")))); _connectionInitializer.InitializeConnectionAsync(null, CancellationToken.None) .ReturnsForAnyArgs(Task.FromResult(new ConnectionDescription( new ConnectionId(serverId), new IsMasterResult(new BsonDocument()), new BuildInfoResult(new BsonDocument("version", "2.6.3"))))); _subject = new BinaryConnection( serverId: serverId, endPoint: _endPoint, settings: new ConnectionSettings(), streamFactory: _streamFactory, connectionInitializer: _connectionInitializer, eventSubscriber: _capturedEvents); }
public async Task<ConnectResult> ConnectAsync(string hostName, int port, string user, string oauth) { if (m_connected) throw new InvalidOperationException("Already connected to twitch chat."); m_endpoint = new DnsEndPoint(hostName, port); m_user = user; m_oauth = oauth; while (true) { try { while (!NativeMethods.IsConnectedToInternet()) Thread.Sleep(5000); m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); return await BeginSocketConnect(); } catch (SocketException) { Log.Irc.ConnectionFailed(); Thread.Sleep(5000); } } }
public string Connect(string hostName, int portNumber) { string result = string.Empty; DnsEndPoint hostEntry = new DnsEndPoint (hostName, portNumber); _socket = new Socket ( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs (); socketEventArg.RemoteEndPoint = hostEntry; socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs> (delegate(object s, SocketAsyncEventArgs e) { result = e.SocketError.ToString (); _clientDone.Set (); } ); _clientDone.Reset (); _socket.ConnectAsync (socketEventArg); _clientDone.WaitOne (TIMEOUT_MILLISECONDS); return result; }
public override bool ConnectAsync(TimeSpan timeout, TransportAsyncCallbackArgs callbackArgs) { // TODO: set socket connect timeout to timeout this.callbackArgs = callbackArgs; DnsEndPoint dnsEndPoint = new DnsEndPoint(this.transportSettings.Host, this.transportSettings.Port); SocketAsyncEventArgs connectEventArgs = new SocketAsyncEventArgs(); connectEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnConnectComplete); connectEventArgs.RemoteEndPoint = dnsEndPoint; connectEventArgs.UserToken = this; #if MONOANDROID // Work around for Mono issue: https://github.com/rabbitmq/rabbitmq-dotnet-client/issues/171 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); bool connectResult = socket.ConnectAsync(connectEventArgs); #else // On Linux platform, socket connections are allowed to be initiated on the socket instance // with hostname due to multiple IP address DNS resolution possibility. // They suggest either using static Connect API or IP address directly. bool connectResult = Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, connectEventArgs); #endif if (connectResult) { return true; } else { this.Complete(connectEventArgs, true); return false; } }
private void button1_Click(object sender, RoutedEventArgs e) { if (loginTB.Text == "") { MessageBox.Show("Задайте имя пользователя"); return; } if (addressTB.Text == "") { MessageBox.Show("Задайте адрес сервера"); return; } DnsEndPoint endPoint; try { endPoint = new DnsEndPoint(addressTB.Text, int.Parse(portTB.Text)); } catch { MessageBox.Show("Неверный адрес сервера"); return; } GameProcess.Inctance.UserName = loginTB.Text; Client.Current.ConnectAsync(endPoint.Host, endPoint.Port); this.Close(); }
public bool Connect() { if (!_isConnected) { if (_consoleIP == "" || _consoleIP == null) return false; _isConnected = false; DnsEndPoint hostEntry = new DnsEndPoint(_consoleIP, _consolePort); _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs(); socketEventArg.RemoteEndPoint = hostEntry; socketEventArg.Completed += (o, args) => { _pausingThread.Set(); }; _pausingThread.Reset(); _socket.ConnectAsync(socketEventArg); _pausingThread.WaitOne(CONNECTION_TIMEOUT_MILLISECONDS); // Send test command _isConnected = IsConnected(); return _isConnected; } else return true; }
public void ForConnectionPool_should_create_expected_message() { var endPoint = new DnsEndPoint("localhost", 27017); var subject = MongoWaitQueueFullException.ForConnectionPool(endPoint); subject.Message.Should().Be("The wait queue for acquiring a connection to server localhost:27017 is full."); }
/// <summary> /// Begins the network communication required to retrieve the time from the NTP server /// </summary> public void RequestTime() { byte[] buffer = new byte[48]; buffer[0] = 0x1B; for (var i = 1; i < buffer.Length; ++i) buffer[i] = 0; DnsEndPoint _endPoint = new DnsEndPoint(_serverName, 123); _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); SocketAsyncEventArgs sArgsConnect = new SocketAsyncEventArgs() { RemoteEndPoint = _endPoint }; sArgsConnect.Completed += (o, e) => { if (e.SocketError == SocketError.Success) { SocketAsyncEventArgs sArgs = new SocketAsyncEventArgs() {RemoteEndPoint = _endPoint}; sArgs.Completed += new EventHandler<SocketAsyncEventArgs>(sArgs_Completed); sArgs.SetBuffer(buffer, 0, buffer.Length); sArgs.UserToken = buffer; _socket.SendAsync(sArgs); } }; _socket.ConnectAsync(sArgsConnect); }
public void Setup() { _capturedEvents = new EventCapturer() .Capture<CommandStartedEvent>() .Capture<CommandSucceededEvent>() .Capture<CommandFailedEvent>(); _streamFactory = Substitute.For<IStreamFactory>(); _endPoint = new DnsEndPoint("localhost", 27017); var serverId = new ServerId(new ClusterId(), _endPoint); _connectionInitializer = Substitute.For<IConnectionInitializer>(); _connectionInitializer.InitializeConnectionAsync(null, CancellationToken.None) .ReturnsForAnyArgs(Task.FromResult(new ConnectionDescription( new ConnectionId(serverId), new IsMasterResult(new BsonDocument()), new BuildInfoResult(new BsonDocument("version", "2.6.3"))))); _subject = new BinaryConnection( serverId: serverId, endPoint: _endPoint, settings: new ConnectionSettings(), streamFactory: _streamFactory, connectionInitializer: _connectionInitializer, eventSubscriber: _capturedEvents); _stream = new BlockingMemoryStream(); _streamFactory.CreateStreamAsync(null, CancellationToken.None) .ReturnsForAnyArgs(Task.FromResult<Stream>(_stream)); _subject.OpenAsync(CancellationToken.None).Wait(); _capturedEvents.Clear(); _operationIdDisposer = EventContext.BeginOperation(); }
public void ResolveDNSAsync(string host, int port) { if (!string.IsNullOrEmpty(host)) { DnsEndPoint endPoint = new DnsEndPoint(host, 80); DeviceNetworkInformation.ResolveHostNameAsync(endPoint, DnsResolutionCallback, new object()); } }
// constructors /// <summary> /// Initializes a new instance of the <see cref="MongoServerInstance"/> class. /// </summary> /// <param name="settings">The settings.</param> /// <param name="address">The address.</param> /// <param name="cluster">The cluster.</param> internal MongoServerInstance(MongoServerSettings settings, MongoServerAddress address, ICluster cluster) { _settings = settings; _address = address; _cluster = cluster; _sequentialId = Interlocked.Increment(ref __nextSequentialId); _endPoint = new DnsEndPoint(address.Host, address.Port); }
public void ToString_should_return_expected_result_when_value_is_a_DnsEndPoint() { var endPoint = new DnsEndPoint("localhost", 27017); var result = EndPointHelper.ToString(endPoint); result.Should().Be("localhost:27017"); }
public SecureTcpClient(string host, int port, TlsClient tlsClient) : base(AddressFamily.InterNetwork) { this.tlsClient = tlsClient; var myEndpoint = new DnsEndPoint(host, port); InnerConnect(myEndpoint); }
public SOCKSNetworkProxy(string host, int port) { #if SILVERLIGHT _address = new DnsEndPoint(host, port, AddressFamily.InterNetwork); #else _host = host; _port = port; #endif }
public NsqLookupConsumerFacts() { lookupEndPoint = new DnsEndPoint(Settings.LookupHostName, Settings.LookupPort); options = new ConsumerOptions { LookupEndPoints = { lookupEndPoint } }; prod = new NsqProducer(Settings.NsqdHostName, Settings.NsqdHttpPort); }
public void TestFixtureSetup() { var clusterId = new ClusterId(1); var clusterType = ClusterType.Standalone; var endPoint = new DnsEndPoint("localhost", 27017); var serverId = new ServerId(clusterId, endPoint); var server = new ServerDescription(serverId, endPoint); var servers = new[] { server }; _clusterDescription = new ClusterDescription(clusterId, clusterType, servers); }
public NsqProducerFacts() { endPoint = new DnsEndPoint(Settings.NsqdHostName, Settings.NsqdTcpPort); options = new ConsumerOptions() { Topic = "foo", Channel = "bar", }; prod = new NsqProducer(Settings.NsqdHostName, Settings.NsqdHttpPort); }
public NsqTcpConnection(DnsEndPoint endPoint, ConsumerOptions options, IBackoffStrategy backoffStrategy) { _endPoint = endPoint; _options = options; _backoffStrategy = backoffStrategy; _connectionClosedSource = new CancellationTokenSource(); _workerThread = new Thread(WorkerLoop); _workerThread.Name = "Turbocharged.NSQ Worker"; }
// static constructor static ClusterDescriptionTests() { __clusterId = new ClusterId(); __endPoint1 = new DnsEndPoint("localhost", 27017); __endPoint2 = new DnsEndPoint("localhost", 27018); __serverId1 = new ServerId(__clusterId, __endPoint1); __serverId2 = new ServerId(__clusterId, __endPoint2); __serverDescription1 = new ServerDescription(__serverId1, __endPoint1); __serverDescription2 = new ServerDescription(__serverId2, __endPoint2); }
public void OneTimeSetUp() { var clusterId = new ClusterId(1); var connectionMode = ClusterConnectionMode.Standalone; var clusterType = ClusterType.Standalone; var endPoint = new DnsEndPoint("localhost", 27017); var serverId = new ServerId(clusterId, endPoint); var server = new ServerDescription(serverId, endPoint); var servers = new[] { server }; _clusterDescription = new ClusterDescription(clusterId, connectionMode, clusterType, servers); }
internal SocketClient(string host, int port) { endPoint = new DnsEndPoint(host, port); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); aborted = false; }
public Socks4Request(Socks4Command cmd, DnsEndPoint remoteEndPoint, string userID = null) : this(cmd, remoteEndPoint.Port, new IPAddress(new byte[] { 0, 0, 0, 1 }), userID ?? string.Empty, remoteEndPoint.Host) { }
/// <param name="defaultPort">If invalid and it's needed to use, then this function returns false.</param> public static bool TryParse(string endPointString, int defaultPort, out EndPoint endPoint) { endPoint = null; try { if (string.IsNullOrWhiteSpace(endPointString)) { return(false); } endPointString = Guard.Correct(endPointString); endPointString = endPointString.TrimEnd(':', '/'); endPointString = endPointString.TrimStart("bitcoin-p2p://", StringComparison.OrdinalIgnoreCase); endPointString = endPointString.TrimStart("tcp://", StringComparison.OrdinalIgnoreCase); var parts = endPointString.Split(':', StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim().TrimEnd('/').TrimEnd()).ToArray(); var isDefaultPortInvalid = !ushort.TryParse(defaultPort.ToString(), out ushort dp) || dp <IPEndPoint.MinPort || dp> IPEndPoint.MaxPort; int port; if (parts.Length == 0) { return(false); } else if (parts.Length == 1) { if (isDefaultPortInvalid) { return(false); } else { port = defaultPort; } } else if (parts.Length == 2) { var portString = parts[1]; if (ushort.TryParse(portString, out ushort p) && p >= IPEndPoint.MinPort && p <= IPEndPoint.MaxPort) { port = p; } else { return(false); } } else { return(false); } string host = parts[0]; if (host == "localhost") { host = IPAddress.Loopback.ToString(); } if (IPAddress.TryParse(host, out IPAddress addr)) { endPoint = new IPEndPoint(addr, port); } else { endPoint = new DnsEndPoint(host, port); } return(true); } catch { return(false); } }
public override bool Equals(object comparand) { DnsEndPoint dep = (comparand as DnsEndPoint); return((comparand != null) && Equals(dep)); }