一个封装不错的 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 ...
随机推荐
- 简单有效:解决 Excel 打开 UTF-8 编码 CSV 文件乱码的 BUG
https://blog.csdn.net/Sukie_csdn/article/details/78752969
- NEST 之旅 · 开启
NEST 之旅 · 开启 Version:5.x 英文原文地址:Getting started 说实话,这篇文章翻译的很糟糕.但是我的能力有限,目前只有这个水平,还望各位多指导. NEST 是 Ela ...
- sendEmail 阿里云使用587端口
使用sendEmail使用参数 -o tls=yes -s smtp服务器+端口 因为阿里云屏蔽了25端口,我使用465也不成功,只有使用587端口,我使用的qq企业邮箱,测试可用
- WebAPI——自动生成帮助文档
Web Api 自动生成帮助文档 新建Web Api项目之后,会在首页有API的导航菜单,点击即可看到API帮助文档,不过很遗憾,Description 是没有内容的. 怎么办呢? 第一步: 如果 ...
- NLS_CHARACTERSET和NLS_NCHAR_CHARACTERSET
The NLS_CHARACTERSET is used for CHAR, VARCHAR2, LONG and CLOB columns;The NLS_NCHAR_CHARACTERSET is ...
- ELK日志分析平台环境部署 (yum安装)
前言:通常体质被分散存储在不同的设备上面,在庞大的服务器集群中,我们需要集中化的管理,日志的统计和检索,一般我们使用grep和awk,wc等linux命令虽然能够实现检索和统计,但是呢,对于要求更高的 ...
- Python学习(二十七)—— Django和pymysql搭建学员管理系统
转载自http://www.cnblogs.com/liwenzhou/p/8270250.html 一.学员管理系统 1.项目规划阶段 项目背景 近年来老男孩教育的入学学员数量稳步快速增长,传统的e ...
- 关于window.open窗口的resize事件
jQuery 事件 - resize() 方法 当调整浏览器窗口的大小时,发生 resize 事件. resize() 方法触发 resize 事件,或规定当发生 resize 事件时运行的函数. & ...
- Codeforces 873E Awards For Contestants ST表
原文链接https://www.cnblogs.com/zhouzhendong/p/9255885.html 题目传送门 - CF873E 题意 现在要给 $n(n\leq 3000)$ 个学生颁奖 ...
- 复制数组之System.arraycopy()的使用
System.arraycopy(src, srcPos, dest, destPos, length); [参数说明](注:arraycopy是一个古老的方法,从jdk1.0就有了,而当时命名并不规 ...