您的位置:首页 > 编程语言 > C#

c#左右socket连接超时控制方案

2015-09-21 20:23 886 查看
之前有一个项目中使用Remoting技术。当远程地址无效或server不执行,访问远程对象的方法,它会经过几十秒的时间来抛出异常秒。

由于我使用tcp状态。因此,认为可以使用socket为了测试连接,它可以调用远程对象之前,该服务没有办法知道远端执行。码如下面:

public class TcpServiceConnect

{

protected EventWaitHandle m_event;

public TcpServiceConnect()

{

m_event = new EventWaitHandle(true, EventResetMode.ManualReset);

}

public void Close()

{

m_event.Set();

}

public bool TryConnect(string ip, int port)

{

m_event.Reset();

var point = new IPEndPoint(IPAddress.Parse(ip), port);

var sok = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

sok.BeginConnect(point, ConnectCallBack, sok);

m_event.WaitOne(3000, false);

bool isConnected = sok.Connected; //事件等结束后。通过这个属性能够知道有没有连续成功

sok.Close();

return isConnected;

}

private void ConnectCallBack(IAsyncResult asyncresult)

{

try

{

var sok = (Socket)asyncresult.AsyncState;

sok.EndConnect(asyncresult);

}

catch { }

m_event.Set();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: