《WinForm开发系列之高级篇》Item2 TCP异步传输
1.AsySocket.cs
代码
public class AsySocket
{
#region 私有字段
private Socket mSocket = null;
private string mID = "";
#endregion
#region 构造函数
public AsySocket(string _LocalIP, int _LocalPort)
{
try
{
mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipe = new IPEndPoint(System.Net.IPAddress.Parse(_LocalIP), _LocalPort);
mID = Guid.NewGuid().ToString();
mSocket.Bind(ipe);
}
catch (Exception e)
{
//初始化Socket错误
}
}
public AsySocket(Socket linkObject)
{
IPEndPoint iep = (IPEndPoint)linkObject.RemoteEndPoint;
mSocket = linkObject;
mID = Guid.NewGuid().ToString();
}
//public void Stop()
//{
// if (mSocket != null)
// {
// mSocket.Close();
// }
//}
#endregion
#region 公共事件
/// <summary>
/// 是否运行
/// </summary>
public bool IsRun = false;
/// <summary>
/// 发送的数据
/// </summary>
public byte[] SendData;
public event AcceptEventHandler onAccept = null;
public event AsySocketClosedEventHandler onClosed = null;
public event StreamDataAcceptHandler onStreamDataAccept = null;
public event StringDataAcceptHandler onStringDataAccept = null;
public event AsySocketEventHandler onSended = null;
public event AsySocketEventHandler onSendTo = null;
/// <summary>
/// 客户端连接建立委托
/// </summary>
/// <param name="AcceptedSocket"></param>
public delegate void AcceptEventHandler(AsySocket AcceptedSocket);
/// <summary>
/// 客户端连接关闭委托
/// </summary>
/// <param name="SocketID"></param>
/// <param name="ErrorMessage"></param>
public delegate void AsySocketClosedEventHandler(AsySocket AcceptedSocket, string ErrorMessage);
/// <summary>
/// 收到数据流委托
/// </summary>
/// <param name="AccepterID"></param>
/// <param name="AcceptData"></param>
public delegate void StreamDataAcceptHandler(AsySocket asySocket, byte[] AcceptData);
/// <summary>
/// Socket事件委托
/// </summary>
/// <param name="SenderID"></param>
/// <param name="EventMessage"></param>
public delegate void AsySocketEventHandler(AsySocket asySocket, string EventMessage);
public delegate void StringDataAcceptHandler(AsySocket asySocket, string AcceptData);
#endregion
#region 公共方法
/// <summary>
/// 监听
/// </summary>
public void Listen(int maxClients)
{
try
{
if (mSocket == null)
throw new ArgumentNullException("连接不存在");
mSocket.Listen(maxClients);
mSocket.BeginAccept(new AsyncCallback(AcceptCallBack), null);//异步
IsRun = true;
}
catch {
IsRun = false;
}
}
/// <summary>
/// 发送二进制数据
/// </summary>
/// <param name="SendData"></param>
public void ASend(byte[] sendData)
{
SendData = sendData;
if (mSocket == null)
throw new ArgumentNullException("连接不存在");
if (SendData == null)
return;
//添加的内容
try
{
mSocket.BeginSend(SendData, 0, SendData.Length, 0, new AsyncCallback(SendCallBack), mSocket);
}
catch
{ }
//sendDone.WaitOne();
}
/// <summary>
/// 发送文本数据
/// </summary>
/// <param name="SendData"></param>
public void ASend(string sendData)
{
SendData = UTF8Encoding.UTF8.GetBytes(sendData);
if (SendData.Length == 0)
return;
this.ASend(UTF8Encoding.UTF8.GetBytes(sendData));
//if (sendData.Length == 0)
// return;
//this.ASend(sendData);
}
/// <summary>
/// UDP发送二进制数据
/// </summary>
/// <param name="SendData"></param>
/// <param name="EndPoint">目标端点</param>
public void ASendTo(byte[] sendData, IPEndPoint EndPoint)
{
if (mSocket == null)
throw new ArgumentNullException("连接不存在");
if (SendData == null)
return;
SendData = sendData;
mSocket.BeginSendTo(SendData, 0, SendData.Length, 0, EndPoint, new AsyncCallback(SendToCallBack), null);
//sendToDone.WaitOne();
}
/// <summary>
/// UDP发送文本数据
/// </summary>
/// <param name="SendData"></param>
/// <param name="EndPoint"></param>
public void ASendTo(string sendData, IPEndPoint EndPoint)
{
if (SendData.Length == 0)
return;
SendData = UTF8Encoding.UTF8.GetBytes(sendData);
ASendTo(UTF8Encoding.UTF8.GetBytes(sendData), EndPoint);
}
/// <summary>
/// 开始接受数据
/// </summary>
public void BeginAcceptData()
{
if (mSocket == null)
throw new ArgumentNullException("连接对象为空");
//开始接收数据
StateObject state = new StateObject();
state.workSocket = mSocket;
mSocket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
//receiveDone.WaitOne();
}
#endregion
#region 公共属性
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
/// <summary>
/// 消息的中止判断符
/// </summary>
public static string EndChar
{
get
{
return new string((char)0, 1);
}
}
public string ID
{
get
{
return mID;
}
}
/// <summary>
/// 发送、接受数据的结尾标志
/// </summary>
public static char LastSign
{
get
{
return (char)0;
}
}
/// <summary>
/// 获取、设置连接对象
/// </summary>
public Socket LinkObject
{
get
{
return mSocket;
}
set
{
mSocket = value;
}
}
public string Address
{
get {
IPEndPoint ep=(IPEndPoint)LinkObject.RemoteEndPoint;
return ep.Address.ToString();
}
}
public int Port
{
get
{
IPEndPoint ep = (IPEndPoint)LinkObject.RemoteEndPoint;
return ep.Port;
}
}
public IPEndPoint EndPoint
{
get
{
IPEndPoint ep = (IPEndPoint)LinkObject.RemoteEndPoint;
return ep;
}
}
#endregion
#region 私有方法
/// <summary>
/// 连接建立处理
/// </summary>
/// <param name="ar"></param>
private void AcceptCallBack(IAsyncResult ar)
{
Socket handler = mSocket.EndAccept(ar);
AsySocket NewSocket = new AsySocket(handler);
//激发事件
if (onAccept != null)
onAccept(NewSocket);
//重新监听
mSocket.BeginAccept(new AsyncCallback(AcceptCallBack), null);
}
/// <summary>
/// 数据接收处理
/// </summary>
/// <param name="ar"></param>
private void ReceiveCallback(IAsyncResult ar)
{
try
{
//
StateObject state = ar.AsyncState as StateObject;
//读取数据
int bytesRead = mSocket.EndReceive(ar);
if (bytesRead > 0)
{
state.sb.Append(UTF8Encoding.UTF8.GetString(state.buffer, 0, bytesRead));
string sb = state.sb.ToString();
//if (sb.Substring(sb.Length - 1, 1) == EndChar)
//{
//接收完成
//激发事件
if (onStreamDataAccept != null)
onStreamDataAccept(this, FuncPlus.SubBytes(state.buffer, 0, bytesRead));
if (onStringDataAccept != null)
onStringDataAccept(this, sb);
//
state = new StateObject();
state.workSocket = mSocket;
//}
// Get the rest of the data.
mSocket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
else
{
//正常关闭
if (onClosed != null)
onClosed(this,"OK");
}
}
catch (SocketException se)
{
if (onClosed != null)
onClosed(this, se.Message);
}
catch (Exception e)
{
throw new ApplicationException(e.Message);
}
}
/// <summary>
/// 发送 处理
/// </summary>
/// <param name="ar"></param>
private void SendCallBack(IAsyncResult ar)
{
try
{
mSocket.EndSend(ar);
//sendDone.Set();
//触发事件
if (onSended != null)
onSended(this, "OK");
}
catch (SocketException se)
{
if (onClosed != null)
onClosed(this, se.Message);
}
catch (Exception e)
{
throw new ApplicationException(e.Message);
}
}
/// <summary>
/// 发送到 处理
/// </summary>
/// <param name="ar"></param>
private void SendToCallBack(IAsyncResult ar)
{
try
{
mSocket.EndSendTo(ar);
//sendToDone.Set();
if (onSendTo != null)
onSendTo(this, "OK");
}
catch (SocketException se)
{
if (onClosed != null)
onClosed(this, se.Message);
}
catch (Exception e)
{
throw new ApplicationException(e.Message);
}
}
#endregion
}
2.AsyTcpCAsyTcpClient.cs
代码
public class AsyTcpClient
{
string _LocalIP;
int _LocalPort=5001;
AsySocket socket = null;
bool _IsRun = false;
public bool IsRun
{
get {
return _IsRun;
}
set {
_IsRun= value;
}
}
#region 构造函数
public AsyTcpClient(string LocalIP, int LocalPort)
{
socket = new AsySocket(LocalIP, LocalPort);
}
public AsyTcpClient(Socket linkObject)
{
socket = new AsySocket(linkObject);
IPEndPoint ep=(IPEndPoint)linkObject.RemoteEndPoint;
_LocalIP = ep.Address.ToString();
_LocalPort = ep.Port;
}
#endregion
#region 公共方法
public bool ConnectServer(string ServerAddress,int ServerPort)
{
//连接
socket = new AsySocket(ServerAddress, 0);
socket.onSended += new AsySocket.AsySocketEventHandler(socket_onSended);
socket.onSendTo += new AsySocket.AsySocketEventHandler(socket_onSendTo);
socket.onStringDataAccept += new AsySocket.StringDataAcceptHandler(socket_onStringDataAccept);
socket.onStreamDataAccept += new AsySocket.StreamDataAcceptHandler(socket_onStreamDataAccept);
socket.onAccept += new AsySocket.AcceptEventHandler(socket_onAccept);
socket.onClosed += new AsySocket.AsySocketClosedEventHandler(socket_onClosed);
try
{
socket.LinkObject.Connect(ServerAddress, ServerPort);
socket.BeginAcceptData();
IsRun = true;
return true;
}
catch
{
IsRun = false;
return false;
}
}
void socket_onClosed(AsySocket AcceptedSocket, string ErrorMessage)
{
this.IsRun = false;
}
void socket_onAccept(AsySocket AcceptedSocket)
{
this.IsRun = true;
}
public void Send(byte[] sendByte)
{
socket.ASend(sendByte);
}
public void Send(string sendData)
{
socket.ASend(sendData);
}
public void DisConnect()
{
if (socket != null && socket.LinkObject.Connected)
{
socket.onSended -= new AsySocket.AsySocketEventHandler(socket_onSended);
socket.onSendTo -= new AsySocket.AsySocketEventHandler(socket_onSendTo);
socket.onStringDataAccept -= new AsySocket.StringDataAcceptHandler(socket_onStringDataAccept);
socket.onStreamDataAccept -= new AsySocket.StreamDataAcceptHandler(socket_onStreamDataAccept);
socket.onAccept -= new AsySocket.AcceptEventHandler(socket_onAccept);
socket.onClosed -= new AsySocket.AsySocketClosedEventHandler(socket_onClosed);
socket.LinkObject.Shutdown(SocketShutdown.Both);
IsRun = false;
}
}
#endregion
void socket_onStreamDataAccept(AsySocket asySocket, byte[] AcceptData)
{
if (onStreamDataAccept != null)
{
onStreamDataAccept(asySocket, AcceptData);
}
}
void socket_onStringDataAccept(AsySocket asySocket, string AcceptData)
{
if (onStringDataAccept != null)
{
onStringDataAccept(asySocket, AcceptData);
}
}
void socket_onSendTo(AsySocket asySocket, string EventMessage)
{
if (onSendTo != null)
{
onSendTo(asySocket, EventMessage);
}
}
void socket_onSended(AsySocket asySocket, string EventMessage)
{
if (onSended != null)
{
onSended(asySocket, EventMessage);
}
}
#region 公共事件
/// <summary>
/// 客户端连接建立委托
/// </summary>
/// <param name="AcceptedSocket"></param>
public delegate void AcceptEventHandler(AsySocket AcceptedSocket);
/// <summary>
/// 客户端连接关闭委托
/// </summary>
/// <param name="SocketID"></param>
/// <param name="ErrorMessage"></param>
public delegate void AsySocketClosedEventHandler(AsySocket ClosedSocket, string ErrorMessage);
/// <summary>
/// 收到数据流委托
/// </summary>
/// <param name="AccepterID"></param>
/// <param name="AcceptData"></param>
public delegate void StreamDataAcceptHandler(AsySocket asySocket, byte[] AcceptData);
/// <summary>
/// Socket事件委托
/// </summary>
/// <param name="SenderID"></param>
/// <param name="EventMessage"></param>
public delegate void AsySocketEventHandler(AsySocket asySocket, string EventMessage);
/// <summary>
/// 收到文本数据委托
/// </summary>
/// <param name="AccepterID"></param>
/// <param name="AcceptData"></param>
public delegate void StringDataAcceptHandler(AsySocket asySocket, string AcceptData);
public event StreamDataAcceptHandler onStreamDataAccept = null;
public event StringDataAcceptHandler onStringDataAccept = null;
public event AsySocketEventHandler onSended = null;
public event AsySocketEventHandler onSendTo = null;
#endregion
}