本文整理汇总了C#中System.Net.Sockets.TcpClient.BeginConnect方法的典型用法代码示例。如果您正苦于以下问题:C# TcpClient.BeginConnect方法的具体用法?C# TcpClient.BeginConnect怎么用?C# TcpClient.BeginConnect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.TcpClient
的用法示例。
在下文中一共展示了TcpClient.BeginConnect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Connect
public Boolean Connect(IPAddress hostAddr, Int32 hostPort, Int32 timeout)
{
// Create new instance of TCP client
_Client = new TcpClient();
var result = _Client.BeginConnect(hostAddr, hostPort, null, null);
_TransmitThread = null;
result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(timeout));
if (!_Client.Connected)
{
return false;
}
// We have connected
_Client.EndConnect(result);
EventHandler handler = OnConnected;
if(handler != null)
{
handler(this, EventArgs.Empty);
}
// Now we are connected --> start async read operation.
NetworkStream networkStream = _Client.GetStream();
byte[] buffer = new byte[_Client.ReceiveBufferSize];
networkStream.BeginRead(buffer, 0, buffer.Length, OnDataReceivedHandler, buffer);
// Start thread to manage transmission of messages
_TransmitThreadEnd = false;
_TransmitThread = new Thread(TransmitThread);
_TransmitThread.Start();
return true;
}
示例2: Client
public Client(TcpClient local, TcpClient remote, String host, int port)
{
_local_client = local;
_remote_client = remote;
_remote_client.BeginConnect(host, port, OnConnect, null);
}
示例3: Connect
public void Connect(int localPort, int remotePort, IPAddress remoteAddress)
{
IPAddress localhost = Dns.GetHostAddresses("127.0.0.1")[0];
listener = new TcpListener(localhost, localPort);
BooleanEventArg arg;
try
{
listener.Start();
}
catch (Exception e)
{
arg = new BooleanEventArg();
arg.result = false;
//localClientConnectedToRemoteServer.Set();
connected(this, arg);
return;
}
listener.BeginAcceptTcpClient(AcceptClient, listener);
client = new TcpClient();
Thread.Sleep(1000);
//localClientConnectedToRemoteServer.Reset();
client.BeginConnect(remoteAddress, remotePort, ServerConnected, client);
//localClientConnectedToRemoteServer.WaitOne();
}
示例4: Connect
public static TcpClient Connect(string host, int port, int timeoutMSec)
{
TimeoutObject.Reset();
socketexception = null;
TcpClient tcpclient = new TcpClient();
tcpclient.BeginConnect(host, port,
new AsyncCallback(CallBackMethod), tcpclient);
if (TimeoutObject.WaitOne(timeoutMSec, false))
{
if (IsConnectionSuccessful)
{
return tcpclient;
}
else
{
throw socketexception;
}
}
else
{
tcpclient.Close();
throw new TimeoutException("TimeOut Exception");
}
}
示例5: Start
public static void Start()
{
if (run == true)
{
Stop();
return;
}
newsysid = 1;
listener.Start();
listener.BeginAcceptTcpClient(DoAcceptTcpClientCallback, listener);
foreach (var portno in portlist)
{
TcpClient cl = new TcpClient();
cl.BeginConnect(IPAddress.Loopback, portno, RequestCallback, cl);
System.Threading.Thread.Sleep(100);
}
th = new System.Threading.Thread(new System.Threading.ThreadStart(mainloop))
{
IsBackground = true,
Name = "stream combiner"
};
th.Start();
MainV2.comPort.BaseStream = new TcpSerial() {client = new TcpClient("127.0.0.1", 5750) };
MainV2.instance.doConnect(MainV2.comPort, "preset", "5750");
}
示例6: CheckMinecraft
public void CheckMinecraft()
{
if (!NeedToUpdate("minecraft", 30))
return;
TcpClient tcp = new TcpClient();
try
{
tcp.SendTimeout = 2000;
tcp.ReceiveTimeout = 2000;
tcp.NoDelay = true;
tcp.Client.ReceiveTimeout = 2000;
tcp.Client.SendTimeout = 2000;
var async = tcp.BeginConnect(MinecraftHost, MinecraftPort, null, null);
DateTime dt = DateTime.Now;
while ((DateTime.Now - dt).TotalSeconds < 3 && !async.IsCompleted)
System.Threading.Thread.Sleep(40);
if (!async.IsCompleted)
{
try
{
tcp.Close();
}
catch { { } }
MinecraftOnline = false;
return;
}
if (!tcp.Connected)
{
log.Fatal("Minecraft server is offline.");
MinecraftOnline = false;
return;
}
var ns = tcp.GetStream();
var sw = new StreamWriter(ns);
var sr = new StreamReader(ns);
ns.WriteByte(0xFE);
if (ns.ReadByte() != 0xFF)
throw new Exception("Invalid data");
short strlen = BitConverter.ToInt16(ns.ReadBytes(2), 0);
string strtxt = Encoding.BigEndianUnicode.GetString(ns.ReadBytes(2 * strlen));
string[] strdat = strtxt.Split('§'); // Description§Players§Slots[§]
MinecraftOnline = true;
MinecraftSvrDescription = strdat[0];
MinecraftCurPlayers = ulong.Parse(strdat[1]);
MinecraftMaxPlayers = ulong.Parse(strdat[2]);
}
catch (Exception n)
{
log.Fatal("Minecraft server check error: " + n);
MinecraftOnline = false;
}
}
示例7: ConnValidate
public static bool ConnValidate(String host, int port, int timeoutMSec)
{
bool ret = false;
timeoutObject.Reset();
socketException = null;
TcpClient tcpClient = new TcpClient();
tcpClient.BeginConnect(host, port, new AsyncCallback(CallBackMethod), tcpClient);
if (timeoutObject.WaitOne(timeoutMSec, false))
{
if (IsConnectionSuccessful)
{
ret = true;
tcpClient.Close();
}
else
{
//throw socketException;
}
}
else
{
//throw new TimeoutException();
}
tcpClient.Close();
return ret;
}
示例8: Ping
public static bool Ping(string host, int port, TimeSpan timeout, out TimeSpan elapsed)
{
using (TcpClient tcp = new TcpClient())
{
DateTime start = DateTime.Now;
IAsyncResult result = tcp.BeginConnect(host, port, null, null);
WaitHandle wait = result.AsyncWaitHandle;
bool ok = true;
try
{
if (!result.AsyncWaitHandle.WaitOne(timeout, false))
{
tcp.Close();
ok = false;
}
tcp.EndConnect(result);
}
catch
{
ok = false;
}
finally
{
wait.Close();
}
DateTime stop = DateTime.Now;
elapsed = stop.Subtract(start);
return ok;
}
}
示例9: startCommLaser
private void startCommLaser()
{
int remotePort = 10002;
String IPAddr = jaguarSetting.LaserRangeIP;
firstSetupComm = true;
try
{
//clientSocket = new TcpClient(IPAddr, remotePort);
clientSocketLaser = new TcpClient();
IAsyncResult results = clientSocketLaser.BeginConnect(IPAddr, remotePort, null, null);
bool success = results.AsyncWaitHandle.WaitOne(500, true);
if (!success)
{
clientSocketLaser.Close();
clientSocketLaser = null;
receivingLaser = false;
pictureBoxLaser.Image = imageList1.Images[3];
}
else
{
receivingLaser = true;
threadClientLaser = new Thread(new ThreadStart(HandleClientLaser));
threadClientLaser.CurrentCulture = new CultureInfo("en-US");
threadClientLaser.Start();
pictureBoxLaser.Image = imageList1.Images[2];
}
}
catch
{
pictureBoxLaser.Image = imageList1.Images[3];
}
}
示例10: Connect
/// <summary>
/// Begins the connection process to the server, including the sending of a handshake once connected.
/// </summary>
public void Connect()
{
try {
BaseSock = new TcpClient();
var ar = BaseSock.BeginConnect(ClientBot.Ip, ClientBot.Port, null, null);
using (ar.AsyncWaitHandle) {
if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false)) {
BaseSock.Close();
ClientBot.RaiseErrorMessage("Failed to connect: Timeout.");
return;
}
BaseSock.EndConnect(ar);
}
} catch (Exception e) {
ClientBot.RaiseErrorMessage("Failed to connect: " + e.Message);
return;
}
ClientBot.RaiseInfoMessage("Connected to server.");
BaseStream = BaseSock.GetStream();
WSock = new ClassicWrapped.ClassicWrapped {_Stream = BaseStream};
DoHandshake();
_handler = new Thread(Handle);
_handler.Start();
_timeoutHandler = new Thread(Timeout);
_timeoutHandler.Start();
}
示例11: IsPortOpen
private static bool IsPortOpen(IPAddress ipAddress, int currentPort, int connectTimeout)
{
bool portIsOpen = false;
using (var tcp = new TcpClient())
{
IAsyncResult ar = tcp.BeginConnect(ipAddress, currentPort, null, null);
using (ar.AsyncWaitHandle)
{
//Wait connectTimeout ms for connection.
if (ar.AsyncWaitHandle.WaitOne(connectTimeout, false))
{
try
{
tcp.EndConnect(ar);
portIsOpen = true;
//Connect was successful.
}
catch
{
//Server refused the connection.
}
}
}
}
return portIsOpen;
}
示例12: Connect
public static TcpClient Connect(IPEndPoint remoteEndPoint, int timeoutMSec)
{
TimeoutObject.Reset();
socketexception = null;
string serverip = Convert.ToString(remoteEndPoint.Address);
int serverport = remoteEndPoint.Port;
TcpClient tcpclient = new TcpClient();
tcpclient.BeginConnect(serverip, serverport,
new AsyncCallback(CallBackMethod), tcpclient);
if (TimeoutObject.WaitOne(timeoutMSec, false))
{
if (IsConnectionSuccessful)
{
return tcpclient;
}
else
{
throw socketexception;
}
}
else
{
tcpclient.Close();
throw new TimeoutException("TimeOut Exception");
}
}
示例13: Start
public static void Start()
{
if (run == true)
{
Stop();
return;
}
newsysid = 1;
listener.Start();
listener.BeginAcceptTcpClient(DoAcceptTcpClientCallback, listener);
foreach (var portno in portlist)
{
TcpClient cl = new TcpClient();
cl.BeginConnect(IPAddress.Loopback, portno, RequestCallback, cl);
System.Threading.Thread.Sleep(500);
}
th = new System.Threading.Thread(new System.Threading.ThreadStart(mainloop))
{
IsBackground = true,
Name = "stream combiner"
};
th.Start();
}
示例14: Connect
public void Connect()
{
if (_client != null) return;
try
{
ReadyState = ReadyStates.CONNECTING;
_client = new TcpClient();
_connecting = true;
_client.BeginConnect(_host, _port, OnRunClient, null);
var waiting = new TimeSpan();
while (_connecting && waiting < ConnectTimeout)
{
var timeSpan = new TimeSpan(0, 0, 0, 0, 100);
waiting = waiting.Add(timeSpan);
Thread.Sleep(timeSpan.Milliseconds);
}
if (_connecting) throw new Exception("Timeout");
}
catch (Exception)
{
Disconnect();
OnFailedConnection(null);
}
}
示例15: Connect
public void Connect()
{
try
{
Close();
}
catch (Exception) { }
client = new TcpClient();
client.NoDelay = true;
IAsyncResult ar = client.BeginConnect(Host, Port, null, null);
System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
try
{
if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
{
client.Close();
throw new IOException("Connection timoeut.", new TimeoutException());
}
client.EndConnect(ar);
}
finally
{
wh.Close();
}
stream = client.GetStream();
stream.ReadTimeout = 10000;
stream.WriteTimeout = 10000;
}