一个封装不错的 TcpClient 类
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace RDavey.Net
{
public class AsyncTcpClient
{
private IPAddress[] addresses;
private int port;
private WaitHandle addressesSet;
private TcpClient tcpClient;
private int failedConnectionCount;
/// <summary>
/// Construct a new client from a known IP Address
/// </summary>
/// <param name="address">The IP Address of the server</param>
/// <param name="port">The port of the server</param>
public AsyncTcpClient(IPAddress address, int port)
: this(new[] { address }, port)
{
}
/// <summary>
/// Construct a new client where multiple IP Addresses for
/// the same client are known.
/// </summary>
/// <param name="addresses">The array of known IP Addresses</param>
/// <param name="port">The port of the server</param>
public AsyncTcpClient(IPAddress[] addresses, int port)
: this(port)
{
this.addresses = addresses;
}
/// <summary>
/// Construct a new client where the address or host name of
/// the server is known.
/// </summary>
/// <param name="hostNameOrAddress">The host name or address of the server</param>
/// <param name="port">The port of the server</param>
public AsyncTcpClient(string hostNameOrAddress, int port)
: this(port)
{
addressesSet = new AutoResetEvent(false);
Dns.BeginGetHostAddresses(hostNameOrAddress, GetHostAddressesCallback, null);
}
/// <summary>
/// Private constuctor called by other constuctors
/// for common operations.
/// </summary>
/// <param name="port"></param>
private AsyncTcpClient(int port)
{
if (port < 0)
throw new ArgumentException();
this.port = port;
this.tcpClient = new TcpClient();
this.Encoding = Encoding.Default;
}
/// <summary>
/// The endoding used to encode/decode string when sending and receiving.
/// </summary>
public Encoding Encoding { get; set; }
/// <summary>
/// Attempts to connect to one of the specified IP Addresses
/// </summary>
public void Connect()
{
if (addressesSet != null)
//Wait for the addresses value to be set
addressesSet.WaitOne();
//Set the failed connection count to 0
Interlocked.Exchange(ref failedConnectionCount, 0);
//Start the async connect operation
tcpClient.BeginConnect(addresses, port, ConnectCallback, null);
}
/// <summary>
/// Writes a string to the network using the defualt encoding.
/// </summary>
/// <param name="data">The string to write</param>
/// <returns>A WaitHandle that can be used to detect
/// when the write operation has completed.</returns>
public void Write(string data)
{
byte[] bytes = Encoding.GetBytes(data);
Write(bytes);
}
/// <summary>
/// Writes an array of bytes to the network.
/// </summary>
/// <param name="bytes">The array to write</param>
/// <returns>A WaitHandle that can be used to detect
/// when the write operation has completed.</returns>
public void Write(byte[] bytes)
{
NetworkStream networkStream = tcpClient.GetStream();
//Start async write operation
networkStream.BeginWrite(bytes, 0, bytes.Length, WriteCallback, null);
}
/// <summary>
/// Callback for Write operation
/// </summary>
/// <param name="result">The AsyncResult object</param>
private void WriteCallback(IAsyncResult result)
{
NetworkStream networkStream = tcpClient.GetStream();
networkStream.EndWrite(result);
}
/// <summary>
/// Callback for Connect operation
/// </summary>
/// <param name="result">The AsyncResult object</param>
private void ConnectCallback(IAsyncResult result)
{
try
{
tcpClient.EndConnect(result);
}
catch
{
//Increment the failed connection count in a thread safe way
Interlocked.Increment(ref failedConnectionCount);
if (failedConnectionCount >= addresses.Length)
{
//We have failed to connect to all the IP Addresses
//connection has failed overall.
return;
}
}
//We are connected successfully.
NetworkStream networkStream = tcpClient.GetStream();
byte[] buffer = new byte[tcpClient.ReceiveBufferSize];
//Now we are connected start asyn read operation.
networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);
}
/// <summary>
/// Callback for Read operation
/// </summary>
/// <param name="result">The AsyncResult object</param>
private void ReadCallback(IAsyncResult result)
{
int read;
NetworkStream networkStream;
try
{
networkStream = tcpClient.GetStream();
read = networkStream.EndRead(result);
}
catch
{
//An error has occured when reading
return;
}
if (read == 0)
{
//The connection has been closed.
return;
}
byte[] buffer = result.AsyncState as byte[];
string data = this.Encoding.GetString(buffer, 0, read);
//Do something with the data object here.
//Then start reading from the network again.
networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);
}
/// <summary>
/// Callback for Get Host Addresses operation
/// </summary>
/// <param name="result">The AsyncResult object</param>
private void GetHostAddressesCallback(IAsyncResult result)
{
addresses = Dns.EndGetHostAddresses(result);
//Signal the addresses are now set
((AutoResetEvent)addressesSet).Set();
}
}
}
一个封装不错的 TcpClient 类的更多相关文章
- Android开发之Toast吐司的一个封装好的工具类。带有源代码java文件,
import android.content.Context; import android.widget.Toast; //Toast统一管理类 public class T { private T ...
- 一个封装的使用Apache HttpClient进行Http请求(GET、POST、PUT等)的类。
一个封装的使用Apache HttpClient进行Http请求(GET.POST.PUT等)的类. import com.qunar.payment.gateway.front.channel.mp ...
- 一个封装比较完整的FTP类——clsFTP
前几天,看见园子里面的博友写了一个支持断点续传的FTP类,一时技痒,干脆写了个更完整的clsFtp类.只是我写这个clsFtp不是支持断点续传的目的,而是为了封装FTP几个基本常用的操作接口. 功能 ...
- TcpClient类与TcpListener类
TcpClient类 //构造方法1 TcpClient t = new TcpClient(); t.Connect(); //构造方法2 IPEndPoint iep = ); TcpClient ...
- Android RecyclerView单击、长按事件:基于OnItemTouchListener +GestureDetector标准实现(二),封装抽取成通用工具类
Android RecyclerView单击.长按事件:基于OnItemTouchListener +GestureDetector标准实现(二),封装抽取成通用工具类 我写的附录文章2,介绍了 ...
- Redis操作Hash工具类封装,Redis工具类封装
Redis操作Hash工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>> ...
- Redis操作字符串工具类封装,Redis工具类封装
Redis操作字符串工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>>& ...
- 一个漂亮的php验证码类
一个漂亮的php验证码类(分享) 作者: 字体:[增加 减小] 类型:转载 下面小编就为大家分享一个漂亮的php验证码类.需要的朋友可以过来参考下 直接上代码: 复制代码 代码如下: //验证 ...
- winform网络编程之TcpClient类,TcpListener类和UdpClient类
TcpClient类和TcpListener类 (1)TcpClient的用途: 用于在同步阻止模式下通过网络来链接.发送和接受流数据,在此情况下,必须有侦听此连接的请求,而侦听的任务就交给TcpLi ...
随机推荐
- 使用Docker方式运行Mysql(MariaDB)
两者差不多.我使用的是MariaDB. 下面的docker命令,挂了数据,配置,映射了端口,指定了root密码,服务端编码. 蛮快的! docker run \ --name mariadb \ -v ...
- rabbitmq3.7.5 centos7 安装笔记
先安装各种依赖文件: yum -y install gcc glibc-devel make ncurses-devel openssl-devel xmlto perl wget vim 1. ra ...
- CentOS6.9安装Filebeat监控Nginx的访问日志发送到Kafka
一.下载地址: 官方:https://www.elastic.co/cn/downloads/beats/filebeat 百度云盘:https://pan.baidu.com/s/1dvhqb0 二 ...
- Redis分布式锁(ServiceStack.Redis实现)
1.设计思路 由于Redis是单线程模型,命令操作原子性,所以利用这个特性可以很容易的实现分布式锁.A用户端在Resdis写入1个KEY,其他的用户无法写入这个KEY,实现锁的效果.A用户使用完成后释 ...
- HDU 1074 Doing Homework(DP状态压缩)
题意:有n门功课需要完成,每一门功课都有时间期限以及你完成所需要的时间,如果完成的时间超出时间期限多少单位,就会被减多少学分,问以怎样的功课完成顺序,会使减掉的学分最少,有多个解时,输出功课名字典序最 ...
- P4714 「数学」约数个数和
题解: 会了Miller-Rabin这题就很简单了 首先这种题很容易想到质因数分解 但是暴力根号算法是不行的 所以要用到 Miller-Rabin素数 https://blog.csdn.net/lt ...
- Linux centos7安装python3并且不影响python2
一.安装依赖 yum -y groupinstall "Development tools" yum -y install zlib-devel bzip2-devel opens ...
- BZOJ5291/洛谷P4458/LOJ#2512 [Bjoi2018]链上二次求和 线段树
原文链接http://www.cnblogs.com/zhouzhendong/p/9031130.html 题目传送门 - LOJ#2512 题目传送门 - 洛谷P4458 题目传送门 - BZOJ ...
- Redis数据库 01概述| 五大数据类型
1.NoSQL数据库简介 解决应用服务器的CPU和内存压力:解决数据库服务的IO压力: ----->>> ① session存在缓存数据库(完全在内存里),速度快且数据结构简单: 打 ...
- quratz数据存储
Quartz 中的 trigger 和 job 需要存储下来才能被使用. 1.两种存储方式 RAMJobStore, JobStoreSupport, 其中 RAMJobStore 是将 trigge ...