本文整理汇总了C#中System.Net.Sockets.Socket.ConnectAsync方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.ConnectAsync方法的具体用法?C# Socket.ConnectAsync怎么用?C# Socket.ConnectAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.Socket
的用法示例。
在下文中一共展示了Socket.ConnectAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: IsPortReachable
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;
}
});
}
示例2: InitConnect
internal void InitConnect(IPEndPoint serverEndPoint,
Action<IPEndPoint, Socket> onConnectionEstablished,
Action<IPEndPoint, SocketError> onConnectionFailed,
ITcpConnection connection,
TimeSpan connectionTimeout)
{
if (serverEndPoint == null)
throw new ArgumentNullException("serverEndPoint");
if (onConnectionEstablished == null)
throw new ArgumentNullException("onConnectionEstablished");
if (onConnectionFailed == null)
throw new ArgumentNullException("onConnectionFailed");
var socketArgs = _connectSocketArgsPool.Get();
var connectingSocket = new Socket(serverEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socketArgs.RemoteEndPoint = serverEndPoint;
socketArgs.AcceptSocket = connectingSocket;
var callbacks = (CallbacksStateToken) socketArgs.UserToken;
callbacks.OnConnectionEstablished = onConnectionEstablished;
callbacks.OnConnectionFailed = onConnectionFailed;
callbacks.PendingConnection = new PendingConnection(connection, DateTime.UtcNow.Add(connectionTimeout));
AddToConnecting(callbacks.PendingConnection);
try
{
var firedAsync = connectingSocket.ConnectAsync(socketArgs);
if (!firedAsync)
ProcessConnect(socketArgs);
}
catch (ObjectDisposedException)
{
HandleBadConnect(socketArgs);
}
}
示例3: Wp7ConnectionDriver
public Wp7ConnectionDriver(Runtime.Runtime runtime, MemoryStream memStream)
: base(false)
{
try
{
_memStream = memStream;
_runtime = runtime;
_runtime.Driver = this;
_incoming = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.Completed += new EventHandler<SocketAsyncEventArgs>(OnConnected);
args.RemoteEndPoint = new DnsEndPoint(HOST, PORT);
if (!_incoming.ConnectAsync(args))
{
OnConnected(null, args);
}
}
catch (SocketException e)
{
throw new ConnectionException(e);
}
}
示例4: SendData
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);
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);
}
}
示例5: ConnectAsync
public static void ConnectAsync(this EndPoint remoteEndPoint, EndPoint localEndPoint, ConnectedCallback callback, object state)
{
var e = CreateSocketAsyncEventArgs(remoteEndPoint, callback, state);
#if NETSTANDARD
if (localEndPoint != null)
{
var socket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.ExclusiveAddressUse = false;
socket.Bind(localEndPoint);
socket.ConnectAsync(e);
}
else
{
Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, e);
}
#else
var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
if (localEndPoint != null)
{
socket.ExclusiveAddressUse = false;
socket.Bind(localEndPoint);
}
socket.ConnectAsync(e);
#endif
}
示例6: ConnectAsyncInternal
private static void ConnectAsyncInternal(this EndPoint remoteEndPoint, EndPoint localEndPoint, ConnectedCallback callback, object state)
{
if (remoteEndPoint is DnsEndPoint)
{
var dnsEndPoint = (DnsEndPoint)remoteEndPoint;
var asyncResult = Dns.BeginGetHostAddresses(dnsEndPoint.Host, OnGetHostAddresses,
new DnsConnectState
{
Port = dnsEndPoint.Port,
Callback = callback,
State = state,
LocalEndPoint = localEndPoint
});
if (asyncResult.CompletedSynchronously)
OnGetHostAddresses(asyncResult);
}
else
{
var e = CreateSocketAsyncEventArgs(remoteEndPoint, callback, state);
var socket = new Socket(remoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
if (localEndPoint != null)
{
socket.ExclusiveAddressUse = false;
socket.Bind(localEndPoint);
}
socket.ConnectAsync(e);
}
}
示例7: SendCommand
private void SendCommand(string command)
{
var data = GetCommandBytes(command);
// Would love to use TcpClient here...
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
var serverAddr = IPAddress.Parse(this.host);
var endPoint = new IPEndPoint(serverAddr, this.port);
var args = new SocketAsyncEventArgs { RemoteEndPoint = endPoint };
args.SetBuffer(data, 0, data.Length);
using (var done = new ManualResetEvent(false))
{
// When there's a buffer present, ConnectAsync sends the data as well
args.Completed += (sender, e) => done.Set();
if (!socket.ConnectAsync(args))
{
throw new Exception("Failed to send command to amplifier");
}
if (!done.WaitOne(TimeSpan.FromSeconds(5)))
{
throw new Exception("Timed out send command to amplifier");
}
}
}
}
示例8: Connect
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;
}
示例9: Open
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;
}
}
示例10: ConnectAsync
public bool ConnectAsync(SocketAsyncEventArgs connectArgs, out Socket socket)
{
socket = Acquire();
if (socket.Connected)
return false;
return socket.ConnectAsync(connectArgs);
}
示例11: ConnectTo
public void ConnectTo(string ip, int port)
{
State = ConnectionState.NotConnected;
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress[] ips = Dns.GetHostAddresses(ip);
var addr = ips[0];
var hostEndPoint = new IPEndPoint(addr, port);
var connectEA = new SocketAsyncEventArgs();
connectEA.RemoteEndPoint = hostEndPoint;
connectEA.Completed += (object sender, SocketAsyncEventArgs e)=>{
switch (e.LastOperation)
{
case SocketAsyncOperation.Connect:
UnityEngine.Debug.Log("Connect success");
break;
default:
throw new ArgumentException("The last operation completed on the socket was not a receive or send");
}
connectEA.Dispose();
State = ConnectionState.Connected;
};
State = ConnectionState.Connecting;
socket.ConnectAsync(connectEA);
}
示例12: Connect
private static Task<Socket> Connect(IPAddress address, int port)
{
var ipe = new IPEndPoint(address, port);
var socket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
var tcs = new TaskCompletionSource<Socket>();
var sea = new SocketAsyncEventArgs();
sea.RemoteEndPoint = ipe;
sea.Completed += (sender, e) =>
{
if (e.SocketError != SocketError.Success)
{
tcs.TrySetException(e.ConnectByNameError);
}
else
{
tcs.TrySetResult(socket);
}
};
socket.ConnectAsync(sea);
return tcs.Task;
}
示例13: ConnectAsync
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;
}
}
示例14: OnSend
void OnSend(object sender, EventArgs args)
{
//定义一个字节数组,并将文本框的的类容转换为字节数组后存入
byte[] bytes = Encoding.UTF8.GetBytes(txtToSend.Text);
//显示信息,可不要。
txtToSend.Text += "/r/nDnsSafeHost:" + Application.Current.Host.Source.DnsSafeHost;
//将同步上下文设置在当前上下文(线程,主线程,可控制UI的)
syn = SynchronizationContext.Current;
//为socket创建示例,并设置相关属性。
socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//定义并实例一个Socket参数
SocketAsyncEventArgs socketArgs = new SocketAsyncEventArgs();
//设置到远程终节点属性(4502端口,为什么是4502,MS的SL通信安全上有)
// socketArgs.RemoteEndPoint = new DnsEndPoint(Application.Current.Host.Source.DnsSafeHost, 4502);
socketArgs.RemoteEndPoint = new IPEndPoint(IPAddress.Parse("10.32.1.219"), 4502);
//new IPEndPoint(IPAddress.Parse(ipadd)
//设置好当Socket任何一个动作完成时的回调函数。
socketArgs.Completed += new EventHandler<SocketAsyncEventArgs>(socketArgs_Completed);
//Socket参数的用户标识,实际上就是一个可以传递的OBJECT参数。
socketArgs.UserToken = bytes;
//执行连接。
socket.ConnectAsync(socketArgs);
}
示例15: ConnectTo
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()));
}
}