本文整理汇总了C#中System.Net.Sockets.Socket.BeginConnect方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.BeginConnect方法的具体用法?C# Socket.BeginConnect怎么用?C# Socket.BeginConnect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.Socket
的用法示例。
在下文中一共展示了Socket.BeginConnect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: button1_Click
private void button1_Click(object sender, EventArgs e)
{
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
var ControllerIPAddress = new IPAddress(new byte[] { 192, 168, 0, 2 });
var ControllerPort = 40001;
var ControllerEndPoint = new IPEndPoint(ControllerIPAddress, ControllerPort);
_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var header = "@";
var command = "00C";
var checksum = "E3";
var end = "\r\n";
var data = header + command + checksum + end;
byte[] bytes = new byte[1024];
//Start Connect
_connectDone.Reset();
watch.Start();
_client.BeginConnect(ControllerIPAddress, ControllerPort, new AsyncCallback(ConnectCallback), _client);
//wait 2s
_connectDone.WaitOne(2000, false);
var text = (_client.Connected) ? "ok" : "ng";
richTextBox1.AppendText(text + "\r\n");
watch.Stop();
richTextBox1.AppendText("Consumer time: " + watch.ElapsedMilliseconds + "\r\n");
}
示例2: ActiveIO
private ActiveIO(Socket ssc, NetSession session, String hostName, int port)
{
(assoc_session = session).InitSession();
//connectDone = new ManualResetEvent(false);
//在 Unity 中 BeginConnect 解析域名阻塞,所以起线程
new Thread(()=>ssc.BeginConnect(hostName, port, new AsyncCallback(ConnectCallback), ssc)).Start();
}
示例3: connectAsync
/**
* Asynchronously connects to the localhost server on the cached port number.
* Sets up a TCP socket attempting to contact localhost:outPort, and a
* corresponding UDP server, bound to the inPort.
*
* UNDONE: Think about establishing TCP communication to request what port to set up,
* in case ports can't be directly forwarded, etc. and Unity doesn't know.
*
* Returns True if the connection was successful, false otherwise.
*/
public bool connectAsync(){
try {
/* Create TCP socket for authenticated communication */
endpt = new IPEndPoint(IPAddress.Parse(host), outPort);
clientAuth = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientAuth.BeginConnect(endpt, new AsyncCallback(connectCallback), clientAuth);
/* Set up nondurable UDP server for receiving actions*/
server = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
server.Blocking = false;
/*Set up nondurable UDP client to send gamestate */
IPEndPoint RemoteEndPoint= new IPEndPoint(IPAddress.Parse(host), outPort);
clientGameState = new Socket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp);
/* Bind to UDP host port */
IPEndPoint inpt = new IPEndPoint(IPAddress.Parse(host), inPort);
server.Bind (inpt);
return true;
} catch (Exception e){
Debug.Log (e);
return false;
}
}
示例4: PooledSocket
public PooledSocket(SocketPool socketPool, IPEndPoint endPoint, int sendReceiveTimeout, int connectTimeout)
{
this.socketPool = socketPool;
Created = DateTime.Now;
//Set up the socket.
socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, sendReceiveTimeout);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, sendReceiveTimeout);
socket.ReceiveTimeout = sendReceiveTimeout;
socket.SendTimeout = sendReceiveTimeout;
//Do not use Nagle's Algorithm
socket.NoDelay = true;
//Establish connection asynchronously to enable connect timeout.
IAsyncResult result = socket.BeginConnect(endPoint, null, null);
bool success = result.AsyncWaitHandle.WaitOne(connectTimeout, false);
if (!success) {
try { socket.Close(); } catch { }
throw new SocketException();
}
socket.EndConnect(result);
//Wraps two layers of streams around the socket for communication.
stream = new BufferedStream(new NetworkStream(socket, false));
}
示例5: PooledSocket
public PooledSocket(IPEndPoint endpoint, TimeSpan connectionTimeout, TimeSpan receiveTimeout)
{
var socket = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
// all operations are "atomic", we do not send small chunks of data
socket.NoDelay = true;
var mre = new ManualResetEvent(false);
var timeout = connectionTimeout == TimeSpan.MaxValue
? Timeout.Infinite
: (int)connectionTimeout.TotalMilliseconds;
socket.ReceiveTimeout = (int)receiveTimeout.TotalMilliseconds;
socket.SendTimeout = (int)receiveTimeout.TotalMilliseconds;
socket.BeginConnect(endpoint, iar =>
{
try { using (iar.AsyncWaitHandle) socket.EndConnect(iar); }
catch { }
mre.Set();
}, null);
if (!mre.WaitOne(timeout) || !socket.Connected)
{
using (socket)
throw new TimeoutException("Could not connect to " + endpoint);
}
this.socket = socket;
this.endpoint = endpoint;
this.inputStream = new BufferedStream(new BasicNetworkStream(socket));
}
示例6: Socket
Task<ActiveConnectResult> IActiveConnector.ActiveConnect(EndPoint targetEndPoint)
{
var taskSource = new TaskCompletionSource<ActiveConnectResult>();
var socket = new Socket(targetEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.BeginConnect(targetEndPoint, OnActiveConnectCallback, new ActiveConnectState(taskSource, socket));
return taskSource.Task;
}
示例7: Scan
public static IEnumerable<int> Scan(string ip, int startPort, int endPort)
{
openPorts.Clear();
//List<int> openPorts = new List<int>();
for (int port = startPort; port <= endPort; port++)
{
Debug.WriteLine(string.Format("Scanning port {0}", port));
Socket scanSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
try
{
//scanSocket.Connect(new IPEndPoint(IPAddress.Parse(ip), port));
//scanSocket.Disconnect(false);
//openPorts.Add(port);
//scanSocket.BeginConnect(new IPEndPoint(ip, port), ScanCallBack, new ArrayList() { scanSocket, port });
scanSocket.BeginConnect(new IPEndPoint(IPAddress.Parse(ip), port), ScanCallBack, new ArrayList() { scanSocket, port });
}
catch (Exception ex)
{
//bury exception since it means we could not connect to the port
}
}
//Computers.comp1.Add(ip, openPorts);
return openPorts;
}
示例8: Connect
public bool Connect( string address, int remotePort )
{
if ( _socket != null && _socket.Connected )
{
return true;
}
//解析域名
IPHostEntry hostEntry = Dns.GetHostEntry( address );
foreach(IPAddress ip in hostEntry.AddressList)
{
try
{
//获得远程服务器的地址
IPEndPoint ipe = new IPEndPoint( ip, remotePort );
//创建socket
_socket = new Socket( ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp );
//开始连接
_socket.BeginConnect( ipe, new System.AsyncCallback( ConnectionCallback ), _socket );
break;
}
catch(System.Exception e)
{
//连接失败 将消息传入逻辑处理队列
PushPacket( (ushort)MessageIdentifiers.ID.CONNECTION_ATTEMPT_FAILED, e.Message );
}
}
return true;
}
示例9: Connect
public static ScanMessage Connect(EndPoint remoteEndPoint, int timeout)
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
TcpConnectCall connectCall = new TcpConnectCall(socket);
// Need for controlling timeout period introduces us to asynccallback methods
AsyncCallback connectedCallback = new AsyncCallback(connectCall.ConnectedCallback);
try
{
IAsyncResult result = socket.BeginConnect(remoteEndPoint, connectedCallback, socket);
// wait for timeout to connect
if (result.AsyncWaitHandle.WaitOne(timeout, false) == false)
{
return ScanMessage.Timeout;
}
else
{
Exception connectException = connectCall.connectFailureException;
if (connectException != null)
{
return ScanMessage.PortClosed;
}
return ScanMessage.PortOpened;
}
}
finally
{
socket.Close();
}
}
示例10: Start
public void Start()
{
try
{
// TODO async resolving
IPAddress ipAddress;
bool parsed = IPAddress.TryParse(config.server, out ipAddress);
if (!parsed)
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(config.server);
ipAddress = ipHostInfo.AddressList[0];
}
IPEndPoint remoteEP = new IPEndPoint(ipAddress, config.server_port);
remote = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
remote.BeginConnect(remoteEP,
new AsyncCallback(connectCallback), null);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
this.Close();
}
}
示例11: btnOK_Click
private void btnOK_Click(object sender, EventArgs e)
{
try
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAddress = IPAddress.Parse(txtServerIP.Text);
//Server is listening on port
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, Convert.ToInt32(txtPort.Text));
//Connect to the server
clientSocket.BeginConnect(ipEndPoint, new AsyncCallback(OnConnect), null);
byteData = new byte[1024];
//Start listening to the data asynchronously
clientSocket.BeginReceive(byteData,
0,
byteData.Length,
SocketFlags.None,
new AsyncCallback(OnReceive),
null);
btnOK.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "ChatClient", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
示例12: connect
public void connect(String Ip, UInt16 port)
{
// Connect to a remote device.
// Establish the remote endpoint for the socket.
// The name of the remote device is Ip.
//Change to these 2 line for Dns resolve
//IPHostEntry ipHostInfo = Dns.GetHostEntry(Ip);
//IPAddress ipAddress = ipHostInfo.AddressList[0];
IPAddress ipAddress = IPAddress.Parse(Ip);
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
tcpClientSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
tcpClientSocket.BeginConnect(remoteEP,
new AsyncCallback(connectCallback), tcpClientSocket);
connectDone.WaitOne(6000);
// Receive the response from the remote device.
// receiveDone.WaitOne();
// Write the response to the console.
// Console.WriteLine("Response received : {0}", response);
// Release the socket.
//client.Shutdown(SocketShutdown.Both);
// client.Close();
receive(tcpClientSocket);
}
示例13: Client_Load
private void Client_Load(object sender, EventArgs e)
{
Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
// Start connecting on load
IAsyncResult result = socket.BeginConnect("cse3461-server.cloudapp.net", 34567, null, null);
// Wait up to 5 seconds
bool success = result.AsyncWaitHandle.WaitOne(5000, true);
// Exit if failed
if (!success)
{
socket.Close();
MessageBox.Show("Unable to Connect", "Unable to connect", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
return;
}
// success, so create a transceiver and hook up events
_xcvr = new MessageXcvr(socket);
_xcvr.Disconnected += _xcvr_Disconnected;
_xcvr.MessageReceived += _xcvr_MessageReceived;
}
示例14: Connect
public void Connect()
{
lock (_lock)
{
if (Connected) return;
var connectEndEvent = new ManualResetEvent(false);
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
_socket.BeginConnect(_config.GatewayIp, _config.GatewayPort, delegate(IAsyncResult result)
{
try
{
var socket = (Socket)result.AsyncState;
socket.EndConnect(result);
}
catch (Exception ex)
{
Console.WriteLine("Unbale to connect, error: {0}.", ex);
}
connectEndEvent.Set();
}, _socket);
if (connectEndEvent.WaitOne(10000) && Connected)
{
_state.Size = CmppConstants.HeaderSize;
_state.PackageType = typeof(CmppHead);
_state.Header = null;
return;
}
Console.WriteLine("Fail to connect to remote host {0}:{1}", _config.GatewayIp, _config.GatewayPort);
Disconnect();
}
}
示例15: StartClient
public static void StartClient()
{
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// The name of the
// remote device is "host.contoso.com".
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
socket = client;
running = true;
// Connect to the remote endpoint.
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
SendReceive(client, "Handshake<EOF>");
}
catch (Exception e)
{
ClientLog(null, new Logging.LogEventArgs(e.ToString()));
}
}