socket测试远程地址能否连接并为连接设置超时

时间:2023-03-10 02:27:13
socket测试远程地址能否连接并为连接设置超时
 public   class TestConnect
{
string hostIp = "";
int port = ;
public string recMsg = "";
Socket socketC = null;
private readonly ManualResetEvent TimeoutObject = new ManualResetEvent(false);
public TestConnect(string hostIp, int port)
{ this.hostIp = hostIp;
this.port = port;
}
public bool connect()
{
///创建终结点(EndPoint)
IPAddress ip = IPAddress.Parse(hostIp);//把ip地址字符串转换为IPAddress类型的实例
IPEndPoint ipe = new IPEndPoint(ip, port);//用指定的端口和ip初始化IPEndPoint类的新实例
///创建socket
socketC = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个socket对像,如果用udp协议,则要用SocketType.Dgram类型的套接字
try
{ return Connect(ipe,); } catch (SocketException ex)
{ socketC.Close();
socketC = null; return false;
} }
/// <summary> /// Socket连接请求 /// </summary> /// <param name="remoteEndPoint">网络端点</param> /// <param name="timeoutMSec">超时时间</param> public bool Connect(IPEndPoint remoteEndPoint, int timeoutMSec)
{ TimeoutObject.Reset(); socketC = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socketC.BeginConnect(remoteEndPoint, CallBackMethod, socketC); //阻塞当前线程 if (TimeoutObject.WaitOne(timeoutMSec, false))
{ return true; } else
{ return false; } } //--异步回调方法 private void CallBackMethod(IAsyncResult asyncresult)
{ //使阻塞的线程继续
Socket socket = asyncresult.AsyncState as Socket; if (socket.Connected)
{
socket.EndConnect(asyncresult); } TimeoutObject.Set(); }
public void testOnline(string msg)
{
socketC.Send(Encoding.GetEncoding("gb2312").GetBytes(msg));       try       {
//创建一个通信线程
ParameterizedThreadStart pts = new ParameterizedThreadStart(ServerRecMsg);
Thread thr = new Thread(pts);
thr.IsBackground = true;
//启动线程
thr.Start(socketC);
      }       catch       { throw ;}     }       /// <summary>
/// 接收客户端发来的信息
/// </summary>
/// <param name="socketClientPara">客户端套接字对象</param>
private void ServerRecMsg(object socketClientPara)
{
Socket socketServer = socketClientPara as Socket;
byte[] arrServerRecMsg = new byte[];
int len;
while ((len = socketServer.Receive(arrServerRecMsg)) != )
{ //将机器接受到的字节数组转换为人可以读懂的字符串
recMsg = Encoding.Default.GetString(arrServerRecMsg, , len); if (recMsg == "online")
{
break;
}
} } }