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();
}
}
由于我使用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();
}
}
相关文章推荐
- c#实现简单计算器
- C# WinForm 设置按纽为透明,使用背景色
- C#_LoadFiles_recursive
- C#中哈希表与List的比较
- C#金额千分位分隔
- C# 使用TimeSpan计算两个时间差
- C#数据缓存介绍及Caching通用帮助类整理
- C#例题3-1简单的程序
- C# HashSet类常用函数
- C#计算代码运行时间,以及总秒数转换为时间格式的问题
- C#图片拼接(全景图片的实现)
- C#随笔
- C#字符串分割
- C# FTP 自动创建目录/上传文件
- C#获取网页源代码的方法
- C# 生成二维码
- C#的类型转换
- C#绘图双缓冲
- c# 在 ComboBox 控件中创建大小可变的文本
- C#泛型类之List<T>