《WinForm开发系列之高级篇》Item2 TCP异步传输
生活随笔
收集整理的這篇文章主要介紹了
《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
}
?
?
轉載于:https://www.cnblogs.com/Sue_/articles/1658264.html
總結
以上是生活随笔為你收集整理的《WinForm开发系列之高级篇》Item2 TCP异步传输的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 设计模式杂谈(一)——设计模式概述
- 下一篇: linux内存单个文件大小,linux