本文整理汇总了C#中TcpClient.BeginConnect方法的典型用法代码示例。如果您正苦于以下问题:C# TcpClient.BeginConnect方法的具体用法?C# TcpClient.BeginConnect怎么用?C# TcpClient.BeginConnect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类TcpClient
的用法示例。
在下文中一共展示了TcpClient.BeginConnect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Connect
public static TcpClient Connect( string ip, ushort port, int timeoutMSec)
{
TimeoutObject.Reset(); // 이벤트 상태를 초기화
socketexception = null; // 예외발생
string serverip = ip; // IP
int serverport = port;
TcpClient tcpclient = new TcpClient();
// 비동기 접속, CallBackMethod
tcpclient.BeginConnect( serverip, serverport, new AsyncCallback( CallBackMethod), tcpclient);
if ( TimeoutObject.WaitOne( timeoutMSec, false)) // 동기화시킨다. timeoutMSec 동안 기다린다.
{
if ( IsConnectionSuccessful) // 접속되는 소켓을
return tcpclient;
else
throw socketexception; // 안되면, 안된 예외를
}
else // 시간이 초과되면
{
tcpclient.Close();
throw new TimeoutException( "TimeOut Exception");
}
}
示例2: Connect
public static bool 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)
{
tcpclient.Close();
return true;
}
else
{
tcpclient.Close();
return false;
}
}
else
{
tcpclient.Close();
return false;
}
}
示例3: TCPClient
public TCPClient(string ipAddress, int port, AsyncCallback connectionHandler)
{
client = new TcpClient();
Debug.Log("lool");
client.BeginConnect(ipAddress, port, connectionHandler, client);
Debug.Log("begin");
}
示例4: HandleConnectionPingCompleted
private void HandleConnectionPingCompleted(object sender, PingCompletedEventArgs e)
{
if (m_TcpClient != null)
{
Disconnect();
}
m_TcpClient = new TcpClient();
m_TcpClient.BeginConnect(Hostname, Port, ConnectComplete, null);
}
示例5: ConnectServer
/// <summary>
/// 连接服务器
/// </summary>
void ConnectServer(string host, int port) {
client = null;
client = new TcpClient();
client.SendTimeout = 1000;
client.ReceiveTimeout = 1000;
client.NoDelay = true;
try {
client.BeginConnect(host, port, new AsyncCallback(OnConnect), null);
} catch (Exception e) {
Close(); Debug.LogError(e.Message);
}
}
示例6: TestConnection
private bool TestConnection(){
TcpClient client = new TcpClient();
bool result = false;
try
{
client.BeginConnect(ip, port, null, null).AsyncWaitHandle.WaitOne(3000);
result = client.Connected;
}
catch { }
finally {
client.Close ();
}
return result;
}
示例7: Connect
public void Connect(string host,int port)
{
this.Host = host;
this.Port = port;
begin = DateTime.Now;
callConnectioneFun = false;
callTimeOutFun = false;
isConnectioned = false;
isbegin = true;
isConnectCall = true;
//Debug.Log("begin connect:" + host + " :" + port + " time:" + begin.ToString());
if (client != null)
client.Close();
client = new TcpClient();
client.BeginConnect(host, port, new AsyncCallback(OnConnected), client);
}
示例8: setupSocket
public void setupSocket()
{
// try {
// host = hostField.text;
// if (string.IsNullOrEmpty(host))
// host = "localhost";
// port = int.Parse(portField.text);
// mySocket = new TcpClient(host, port);
// theStream = mySocket.GetStream();
// theWriter = new StreamWriter(theStream);
// theReader = new StreamReader(theStream);
// theReader.BaseStream.ReadTimeout = 1000;
// socketReady = true;
// Debug.Log ("Connected");
// menu.SetActive(false);
// world.SetActive(true);
// EventsManager.em.speedController.SetActive (true);
// }
try {
host = hostField.text;
if (string.IsNullOrEmpty(host))
host = "localhost";
port = int.Parse(portField.text);
mySocket = new TcpClient();
var result = mySocket.BeginConnect(host, port, null, null);
bool success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2));
if (!success)
throw new Exception("Connection timed out.");
mySocket.EndConnect(result);
theStream = mySocket.GetStream();
theWriter = new StreamWriter(theStream);
theReader = new StreamReader(theStream);
theReader.BaseStream.ReadTimeout = 1000;
socketReady = true;
Debug.Log ("Connected");
menu.SetActive(false);
world.SetActive(true);
EventsManager.em.speedController.SetActive (true);
EventsManager.em.dallesPanels.SetActive (true);
}
catch (Exception e) {
Debug.Log("Socket error: " + e);
EventsManager.em.msgBox.ServerMessage("Connection failed: " + e.Message, Color.red);
//Application.LoadLevel(0);
}
}
示例9: Start
//public CNj
//public BotControlScript botControllScript;
// Use this for initialization
void Start () {
//init
commandList = new ArrayList ();
if (UsingProxy)
{
proxySocket = new TcpClient ();
proxySocket.BeginConnect (ProxyURL, ProxyPort, new System.AsyncCallback (ProxySuccess),proxySocket);
}
else
{
this.tcpListener = new TcpListener(IPAddress.Any, serverPort);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
string localIP = LocalIPAddress ();
Debug.Log ("Server Start on:"+localIP);
ParseObject testObject = new ParseObject("GlassGame");
testObject["ip"] = localIP;
testObject.SaveAsync().ContinueWith(temp=>
{
var query = ParseObject.GetQuery("GlassGame").OrderByDescending("createdAt").Limit(1);
query.FirstAsync().ContinueWith(t =>
{
ParseObject obj = t.Result;
Debug.Log("Insert Parse ip:"+obj["ip"]);
Debug.Log("Parse Date:"+obj.CreatedAt);
});
});
}
示例10: Connect
/// <summary>
/// 异步连接
/// </summary>
public void Connect()
{
if ((tcp == null) || (!tcp.Connected))
{
try
{
new Thread(() =>
{
tcp = new TcpClient();
tcp.ReceiveTimeout = 10;
connectDone.Reset();
SetText("Establishing Connection to Server");
tcp.BeginConnect("218.244.145.129", 12345,
new AsyncCallback(ConnectCallback), tcp);
connectDone.WaitOne();
if ((tcp != null) && (tcp.Connected))
{
workStream = tcp.GetStream();
SetText("Connection established");
asyncread(tcp);
}
}).Start();
}
catch (Exception se)
{
Console.WriteLine(se.Message + " Conn......." + Environment.NewLine);
}
}
}
示例11: ConnectServer
/// <summary>
/// 连接服务器
/// </summary>
void ConnectServer(string host, int port) {
client = null;
client = new TcpClient();
client.SendTimeout = 1000;
client.ReceiveTimeout = 1000;
client.NoDelay = true;
try {
client.BeginConnect(host, port,new AsyncCallback(OnConnect),null);
} catch (Exception e) {
Close();
//Debug.LogError(e.Message);
sockteClientState = netState.None;
lock (NetworkManager.sEvents)
{
NetworkManager.AddEvent(Protocal.ConnectFailer, new ByteBuffer());
}
}
}
示例12: ConnectTo
void ConnectTo(string ip)
{
if (usingProxy)
{
Debug.Log ("Connecting to " + ip);
client = new TcpClient ();
client.BeginConnect (proxyHost, proxyPort, new System.AsyncCallback (ProcessDnsInformation), client);
}
else
{
Debug.Log ("Connecting to " + ip);
client = new TcpClient ();
client.BeginConnect (ip, port, new System.AsyncCallback (ProcessDnsInformation), client);
}
}
示例13: updateServers
/*
* this method iterates through each known server,
* issues a GETS to each server, and then if any line contains
* new server info, it is added into knownServers.
*/
public void updateServers()
{
TcpClient c = new TcpClient();
for (int i = 0; i < GameMatchingServer.knownServers.Count; i++) {
Server s = (Server) GameMatchingServer.knownServers[i];
// to avoid connecting to self, which would cause an infinite loop.
if (s.port != GameMatchingServer.port) {
try {
c = new TcpClient();
var result = c.BeginConnect(s.IP, s.port, null, null);
var success = result.AsyncWaitHandle.WaitOne(5000, true);
if(!success) {
c.Close();
continue;
} else if (c.Connected) {
//c.Connect(s.IP, s.port);
Stream str = c.GetStream();
StreamWriter strW = new StreamWriter(str);
StreamReader strR = new StreamReader(str);
strW.AutoFlush = true;
// Login as ourselves.
strW.WriteLine("SERVER {0}:{1}", GameMatchingServer.port,
GameMatchingServer.nickName);
strR.ReadLine();
string TwoHundredTest = strR.ReadLine();
while (TwoHundredTest.StartsWith("100")) {
TwoHundredTest = strR.ReadLine();
}
// loop reads all responses from client so far.
// while (!strR.EndOfStream) {
// Console.WriteLine(strR.ReadLine());
// }
strW.WriteLine("GETS");
ArrayList responses = new ArrayList();
string[] getSResp;
int k = 0;
responses.Add(strR.ReadLine());
while (((string)responses[k]).StartsWith("-200")) {
k++;
responses.Add(strR.ReadLine());
} // all -200's should be in string array.
getSResp = (String[]) responses.ToArray(typeof(string));
parseAndAdd(getSResp);
str.Close();
c.Close();
}
} catch (SocketException ex) {
Console.WriteLine(ex);
Console.WriteLine("Connection Error with server at {0}:{1}", s.IP, s.port);
} catch (Exception e) {
c.Close();
Console.WriteLine(e);
}
}
}
}
示例14: BeginConnect
public ProxyAsyncState BeginConnect(IPAddress address, AsyncCallback callback, object state)
{
AsyncConnection conn;
lock (_connections)
if (_connections.TryGetValue(new IPEndPoint(address, PortNumber), out conn))
{
return new ProxyAsyncState(conn.Proxy, state);
}
TcpClient client = new TcpClient();
try
{
lock (_unfinishedConnections)
_unfinishedConnections.Add(address, client);
}
catch (ArgumentException)
{
throw new InvalidOperationException("Connection is under way.");
}
PeerProxy proxy = CreateProxy();
try
{
client.BeginConnect(address, PortNumber, callback,
Tuple.Create(new ConnectionAsyncResult(client, proxy, state), address));
}
catch (Exception)
{
lock (_unfinishedConnections)
_unfinishedConnections.Remove(address);
throw new CannotConnectException();
}
return new ProxyAsyncState(proxy, state);
}
示例15: ConnectionCoroutine
// Coroutine for managing the connection.
IEnumerator ConnectionCoroutine ()
{
// "Active Sense" message for heartbeating.
var heartbeat = new byte[4] {0xfe, 0xff, 0xff, 0xff};
while (true) {
// Try to open the connection.
for (var retryCount = 0;; retryCount++) {
// Start to connect.
var tempClient = new TcpClient ();
tempClient.BeginConnect (IPAddress.Loopback, portNumber, ConnectCallback, null);
// Wait for callback.
isConnecting = true;
while (isConnecting) {
yield return null;
}
// Break if the connection is established.
if (tempClient.Connected) {
tcpClient = tempClient;
break;
}
// Dispose the connection.
tempClient.Close ();
tempClient = null;
// Show warning and wait a second.
if (retryCount % 3 == 0) {
Debug.LogWarning ("Failed to connect to MIDI Bridge. Make sure to run MidiBridge.exe");
}
yield return new WaitForSeconds (1.0f);
}
// Watch the connection.
while (tcpClient.Connected) {
yield return new WaitForSeconds (1.0f);
// Send a heartbeat and break if it failed.
try {
tcpClient.GetStream ().Write (heartbeat, 0, heartbeat.Length);
} catch (System.IO.IOException exception) {
Debug.Log (exception);
}
}
// Show warning.
Debug.LogWarning ("Disconnected from MIDI Bridge.");
// Close the connection and retry.
tcpClient.Close ();
tcpClient = null;
}
}