using AD.SocketForm.Model;
using NLog;
using System;
using System.Net.Sockets;
using System.Threading; namespace AD.SocketForm.Service
{
/// <summary>
/// Socket连接类-可指定超时时间
/// 参考网址://www.cnblogs.com/weidagang2046/archive/2009/02/07/1385977.html
/// </summary>
public class SocketNewService
{
private Logger _logger = LogManager.GetCurrentClassLogger(); /// <summary>
/// 连接socket
/// </summary>
/// <param name="model"></param>
/// <param name="timeout">单位:毫秒</param>
/// <returns></returns>
public Socket Create(HubModel model, int timeout)
{
var isConnected = false;
var manualResetEvent = new ManualResetEvent(false);
var tcpClient = new TcpClient(); #region 异步方法委托
Action<IAsyncResult> action = (asyncresult) =>
{
try
{
TcpClient tcpclient = asyncresult.AsyncState as TcpClient; if (tcpclient.Client != null)
{
tcpclient.EndConnect(asyncresult);
isConnected = true;
}
//Thread.Sleep(1000);
}
catch (Exception ex)
{
_logger.Error(string.Format("获取socket异常,message:{0},stacktrace:{1}", ex.Message, ex.StackTrace));
isConnected = false;
}
finally
{
manualResetEvent.Set();
}
};
#endregion tcpClient.BeginConnect(model.IP, model.Port, new AsyncCallback(action), tcpClient); //判断在指定的时间以内是否收到释放锁的通知
if (manualResetEvent.WaitOne(timeout, false))
{
//Console.WriteLine("连接成功");
if (isConnected)
{
return tcpClient.Client;
}
else
{
return null;
}
}
else
{
//Console.WriteLine("超时");
tcpClient.Close();
return null;
}
} /// <summary>
/// 关闭socket
/// </summary>
/// <param name="socket"></param>
public void Close(Socket socket)
{
if (socket != null)
{
socket.Close();
socket = null;
}
} /// <summary>
/// 判断Socket是否已连接
/// </summary>
/// <param name="socket"></param>
/// <returns></returns>
public bool IsConnected(Socket socket)
{
if (socket == null || socket.Connected == false)
{
return false;
} bool blockingState = socket.Blocking;
try
{
byte[] tmp = new byte[];
socket.Blocking = false;
socket.Send(tmp, , );
return true;
}
catch (SocketException e)
{
// 产生 10035 == WSAEWOULDBLOCK 错误,说明被阻止了,但是还是连接的
if (e.NativeErrorCode.Equals())
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
_logger.Error(string.Format("检查Socket是否可连接时异常,message:{0},stacktrace:{1}", ex.Message, ex.StackTrace));
return false;
}
finally
{
socket.Blocking = blockingState; // 恢复状态
}
}
}
}

主要是通过两点:

1、通过if (manualResetEvent.WaitOne(timeout, false))来处理。它的作用是:阻止当前线程N毫秒,期间如果有调用manualResetEvent.Set()立即取消当前线程的阻塞,并且返回true;如果没有调用,时间到了后依然取消当前线程的阻塞,但是返回false。

2、通过tcpClient.BeginConnect(model.IP, model.Port, new AsyncCallback(action), tcpClient)建立tcp连接。这句话的意思是以异步的方式建立tcp连接,成功之后调用指定的回调方法。即new AsyncCallback(action)。

另外,这个类把回调方法写在了Create方法里面,原因是方便处理isConnected的状态,无需考虑线程同步。因为这个辅助类实例化后,是被驻留在内存里面的,有可能会被多次使用。为了线程安全,所以写在了里面。

c# 创建socket连接辅助类-可指定超时时间的更多相关文章

  1. c# 创建socket连接辅助类

    using AD.SocketForm.Model; using NLog; using System; using System.Net; using System.Net.Sockets; nam ...

  2. Socket超时时间设置

    你知道在 Java 中怎么对 Socket 设置超时时间吗?他们的区别是什么?想一想和女朋友打电话的场景就知道了,如果实在想不到,那我们就一起来来看一下是咋回事吧 设置方式 主要有以下两种方式,我们来 ...

  3. Http和Socket连接区别

    相信不少初学手机联网开发的朋友都想知道Http与Socket连接究竟有什么区别,希望通过自己的浅显理解能对初学者有所帮助. 1.TCP连接 要想明白Socket连接,先要明白TCP连接.手机能够使用联 ...

  4. Http、tcp、Socket连接区别

    转自Http.tcp.Socket连接区别 相信不少初学手机联网开发的朋友都想知道Http与Socket连接究竟有什么区别,希望通过自己的浅显理解能对初学者有所帮助. 1.TCP连接 要想明白Sock ...

  5. Http和Socket连接的区别

    Http和Socket连接区别 相信不少初学手机联网开发的朋友都想知道Http与Socket连接究竟有什么区别,希望通过自己的浅显理解能对初学者有所帮助. 1.TCP连接 要想明白Socket连接,先 ...

  6. Http和Socket连接

    转自http://hi.baidu.com/%D2%B9%D1%A9%B3%E6/blog/item/d6a72d2bbf467cf2e7cd406d.html 相信不少初学手机联网开发的朋友都想知道 ...

  7. TCP连接、Http连接与Socket连接

    1.TCP连接 手机能够使用联网功能是因为手机底层实现了TCP/IP协议,可以使手机终端通过无线网络建立TCP连接.TCP协议可以对上层网络提供接口,使上层网络数据的传输建立在“无差别”的网络之上. ...

  8. Socket设置超时时间

    主要有以下两种方式,我们来看一下方式1: Socket s=new Socket(); s.connect(new InetSocketAddress(host,port),10000); 方式2: ...

  9. timeout Timeout时间已到.在操作完成之前超时时间已过或服务器未响应

    Timeout时间已到.在操作完成之前超时时间已过或服务器未响应 问题 在使用asp.net开发的应用程序查询数据的时候,遇到页面请求时间过长且返回"Timeout时间已到.在操作完成之间超 ...

随机推荐

  1. EF Core中如何设置数据库表自己与自己的多对多关系

    本文的代码基于.NET Core 3.0和EF Core 3.0 有时候在数据库设计中,一个表自己会和自己是多对多关系. 在SQL Server数据库中,现在我们有Person表,代表一个人,建表语句 ...

  2. node、npm、gulp安装

    1.先安装node.js ,官网下载地址:https://nodejs.org/en/ 2.安装完node之后,npm自动就安装了.可以直接在visual studio code 通过命令查看 nod ...

  3. Asp.NetCoreWebApi - RESTful Api

    目录 参考文章 REST 常用http动词 WebApi 在 Asp.NetCore 中的实现 创建WebApi项目. 集成Entity Framework Core操作Mysql 安装相关的包(为X ...

  4. DISK2VHD 转win2008 无法启动

    windows 2008R2物理机,使用微软的DISK2VHD转换成虚拟盘,挂到虚拟机上,无法启动只有光标闪.找来window2008安装盘 选择“修复windows系统”, 调出cmd命令提示符Bo ...

  5. NLog日志

    配置nlog 1.从nuget中获取配置 安装前2个文件 然后会有一个NLog.config 更改内容 <?xml version="1.0" encoding=" ...

  6. 要什么 Photoshop,会这些 CSS 就够了

    标题党一时爽,一直标题党一直爽 还在上大学那会儿,我就喜欢玩 Photoshop.后来写网页的时候,由于自己太菜,好多花里胡哨的效果都得借助 Photoshop 实现,当时就特别希望 CSS 能像 P ...

  7. 【转载】Gradle学习 第八章:依赖管理基础

    转载地址:http://ask.android-studio.org/?/article/10 This chapter introduces some of the basics of depend ...

  8. .net web api 权限验证

    做一个登录权限验证. 开始吧. using System; using System.Collections.Generic; using System.Drawing; using System.D ...

  9. Python可视化查看数据集完整性: missingno库(用于数据分析前的数据检查)

    数据分析之前首先要保证数据集的质量,missingno库提供了一个灵活易用的可视化工具来观察数据缺失情况,是基于matplotlib的,接受pandas数据源 快速开始 样例数据使用 NYPD Mot ...

  10. 使用Python3导出MySQL查询数据

    整理个Python3导出MySQL查询数据d的脚本. Python依赖包: pymysql xlwt Python脚本: #!/usr/bin/env python # -*- coding: utf ...