一个封装不错的 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();
}
}
}

时间: 2024-11-05 11:37:54

一个封装不错的 TcpClient 类的相关文章

初学者如何新建一个封装的类来封装方法

第一步 AppDelegate中引用导航器,并设置根视图,同时隐藏导航栏 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for c

模块的封装之C语言类的继承和派生

[交流][微知识]模块的封装(二):C语言的继承和派生 在模块的封装(一):C语言的封装中,我们介绍了如何使用C语言的结构体来实现一个类的封装,并通过掩码结构体的方式实 现了类成员的保护.这一部分,我们将 在此的基础上介绍C语言类的继承和派生.其实继承和派生是一个动作的两种不同角度的表达 .当我们继承了一个基类而创造了一个新类时,派生的概念就诞生了.派生当然是从基类派生的.派生出来的类当然是继承了基类的 东西.继承和派生不是一对好基友,他们根本就是一个动作的两种不同的说法,强调动作的起始点的时候

模块的封装之C语言类的封装

[微知识]模块的封装(一):C语言类的封装 是的,你没有看错,我们要讨论的是C语言而不是C++语言中类的封装.在展开知识点之前,我首先要 重申两点: 1.面向对象是一种思想,基本与所用的语言是无关的.当你心怀面向对象时,即使使用QBasic也能写 出符合面向对象思想的代码,更不要说C语言了.举一个反例,很多人初学C++的时候,并没有掌 握面向对象的思想,活生生的把类当结构体来使用的也不在少数吧. 2.面向对象的最基本的出发点是“将数据以及处理数据的方法封装在一起”,至于继承.派生.多态之类 的则

利用Java针对MySql封装的jdbc框架类 JdbcUtils 完整实现(包含增删改查、JavaBean反射原理,附源码)

最近看老罗的视频,跟着完成了利用Java操作MySql数据库的一个框架类JdbcUtils.java,完成对数据库的增删改查.其中查询这块,包括普通的查询和利用反射完成的查询,主要包括以下几个函数接口: 1.public Connection getConnection()   获得数据库的连接 2.public boolean updateByPreparedStatement(String sql, List<Object>params)throws SQLException  更新数据库

【Android】19.3 ContentProvider及安卓进一步封装后的相关类

分类:C#.Android.VS2015: 创建日期:2016-03-08 一.简介 ContentProvider:内容提供程序. Android的ContentProvider与.NET框架的EF(Entity Framework)非常类似.在EF中,每个类表示数据库中的一个表,类中的每个属性对应表的字段,类的每个实例表示数据库表的一行记录.同样,在Android中,每个ContentProvider类的实例表示数据表的一行记录,ContentProvider实例集合中的每一项表示数据表中的

Android RecyclerView单击、长按事件:基于OnItemTouchListener +GestureDetector标准实现(二),封装抽取成通用工具类

?? Android RecyclerView单击.长按事件:基于OnItemTouchListener +GestureDetector标准实现(二),封装抽取成通用工具类 我写的附录文章2,介绍了Android如何基于OnItemTouchListener +GestureDetector实现单击.长按事件的监听,由于如今RecyclerView在Android开发是如此的普遍,以及RecyclerView的单击事件是如此的常用,如果像附录文章2那样把一堆事件监听写到业务逻辑代码里面,那得写

TcpClient类与TcpListener类

TcpClient类 1 //构造方法1 2 TcpClient t = new TcpClient(); 3 t.Connect("www.163.com", 8000); 4 //构造方法2 5 IPEndPoint iep = new IPEndPoint(IPAddress.Parse("192.168.10.27"),8000); 6 TcpClient t2 = new TcpClient(iep); 7 t2.Connect("www.163

Thread并发请求封装——深入理解AsyncTask类

在Android开发中,由于不能再UI线程中做耗时操作,常常需要开启线程来做一些操作.但是这样一来就产生了一个问题,就是大量的线程并发执行,造成了线程维护的开销进而使得代码质量下降手机发烫又耗电.让我们来看一下KJFrameForAndroid框架是如何解决这个问题的.KJFrameForAndroid框架项目地址:https://github.com/kymjs/KJFrameForAndroid. 其实Android提供了一套专门用于异步处理的类,就是我们熟悉又模式的AsynTask类.As

一个漂亮的php验证码类

一个漂亮的php验证码类(分享) 作者: 字体:[增加 减小] 类型:转载 下面小编就为大家分享一个漂亮的php验证码类.需要的朋友可以过来参考下 直接上代码: 复制代码 代码如下: //验证码类class ValidateCode { private $charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789';//随机因子 private $code;//验证码 private $codelen = 4;//验证码长度 pri