You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
74 lines
2.2 KiB
C#
74 lines
2.2 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Net.Sockets;
|
|
using System.Net;
|
|
|
|
namespace demo.ClassHelper.SyncSocket
|
|
{
|
|
class SyncClient
|
|
{
|
|
private static bool IsConnectionSuccessful = false;
|
|
private static Exception socketexception;
|
|
private static System.Threading.ManualResetEvent TimeoutObject = new System.Threading.ManualResetEvent(false);
|
|
|
|
public static IPEndPoint CreateIPEndPoint(string ip, int port)
|
|
{
|
|
IPAddress ipAddress = StringToIPAddress(ip);
|
|
return new IPEndPoint(ipAddress, port);
|
|
}
|
|
|
|
public static IPAddress StringToIPAddress(string ip)
|
|
{
|
|
return IPAddress.Parse(ip);
|
|
}
|
|
|
|
public static Socket Connect(IPEndPoint remoteEndPoint, int timeoutMSec)
|
|
{
|
|
TimeoutObject.Reset();
|
|
socketexception = null;
|
|
|
|
Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
|
socketClient.BeginConnect(remoteEndPoint, new AsyncCallback(CallBackMethod), socketClient);
|
|
|
|
if (TimeoutObject.WaitOne(timeoutMSec, false))
|
|
{
|
|
if (IsConnectionSuccessful)
|
|
return socketClient;
|
|
else
|
|
throw socketexception;
|
|
}
|
|
else
|
|
{
|
|
socketClient.Close();
|
|
throw new TimeoutException("TimeOut Exception");
|
|
}
|
|
|
|
}
|
|
private static void CallBackMethod(IAsyncResult asyncresult)
|
|
{
|
|
try
|
|
{
|
|
IsConnectionSuccessful = false;
|
|
Socket socketClient = asyncresult.AsyncState as Socket;
|
|
|
|
if (socketClient != null)
|
|
{
|
|
socketClient.EndConnect(asyncresult);
|
|
IsConnectionSuccessful = true;
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
IsConnectionSuccessful = false;
|
|
socketexception = ex;
|
|
}
|
|
finally
|
|
{
|
|
TimeoutObject.Set();
|
|
}
|
|
}
|
|
}
|
|
}
|