新增TCP扩展
This commit is contained in:
1 parent
514d6f5255
commit
f119665d29
26 files changed
+2457
-34
No files matched your search
@@ -0,0 +1,557 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Configuration;
|
||||
|
||||
namespace HHWMS.Web
|
||||
{
|
||||
/// <summary>
|
||||
/// Socket客户端类,连接App.Config中FeedingIP:Port
|
||||
/// </summary>
|
||||
public class SocketClient : IDisposable
|
||||
{
|
||||
#region 字段、委托、事件
|
||||
|
||||
//private static SocketClient instance = null;
|
||||
/// <summary>
|
||||
/// 客户端连接Socket
|
||||
/// </summary>
|
||||
private Socket clientSocket;
|
||||
/// <summary>
|
||||
/// 连接状态
|
||||
/// </summary>
|
||||
private Boolean connected = false;
|
||||
/// <summary>
|
||||
/// 连接点
|
||||
/// </summary>
|
||||
private IPEndPoint hostEndPoint;
|
||||
/// <summary>
|
||||
/// 连接信号量
|
||||
/// </summary>
|
||||
//private static AutoResetEvent autoConnectEvent = new AutoResetEvent(false);
|
||||
/// <summary>
|
||||
/// 接受到数据时的委托
|
||||
/// </summary>
|
||||
/// <param name="info"></param>
|
||||
public delegate void ReceiveMsgHandler(byte[] info);
|
||||
/// <summary>
|
||||
/// 接收到数据时调用的事件
|
||||
/// </summary>
|
||||
public event ReceiveMsgHandler OnMsgReceived;
|
||||
/// <summary>
|
||||
/// 开始监听数据的委托
|
||||
/// </summary>
|
||||
public delegate void StartListenHandler();
|
||||
/// <summary>
|
||||
/// 开始监听数据的事件
|
||||
/// </summary>
|
||||
public event StartListenHandler StartListenThread;
|
||||
|
||||
/// <summary>
|
||||
/// 连接失败的委托
|
||||
/// </summary>
|
||||
public delegate void ConnectFailHandler();
|
||||
/// <summary>
|
||||
/// 连接失败的事件
|
||||
/// </summary>
|
||||
public event ConnectFailHandler ConnectFail;
|
||||
|
||||
/// <summary>
|
||||
/// 发送信息完成的委托
|
||||
/// </summary>
|
||||
/// <param name="successorfalse"></param>
|
||||
public delegate void SendCompleted(bool successorfalse);
|
||||
/// <summary>
|
||||
/// 发送信息完成的事件
|
||||
/// </summary>
|
||||
public event SendCompleted OnSended;
|
||||
/// <summary>
|
||||
/// 监听接收的SocketAsyncEventArgs
|
||||
/// </summary>
|
||||
private SocketAsyncEventArgs listenerSocketAsyncEventArgs;
|
||||
/// <summary>
|
||||
/// 心跳时钟
|
||||
/// </summary>
|
||||
private System.Timers.Timer _timer = null;
|
||||
/// <summary>
|
||||
/// SocketServer服务器IP
|
||||
/// </summary>
|
||||
public string hostName;
|
||||
/// <summary>
|
||||
/// SocketServer服务器端口号
|
||||
/// </summary>
|
||||
public int port;
|
||||
|
||||
#endregion
|
||||
|
||||
#region 属性定义
|
||||
|
||||
/// <summary>
|
||||
/// SocketServer服务器IP地址
|
||||
/// </summary>
|
||||
string _serverIp;
|
||||
public string ServerIp
|
||||
{
|
||||
get
|
||||
{
|
||||
return _serverIp;
|
||||
}
|
||||
set
|
||||
{
|
||||
_serverIp = value;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// SocketServer服务器端口号
|
||||
/// </summary>
|
||||
///
|
||||
string _serverPort;
|
||||
public string ServerPort
|
||||
{
|
||||
get
|
||||
{
|
||||
return _serverPort;
|
||||
}
|
||||
set
|
||||
{
|
||||
_serverPort = value;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 是否处于连接状态,需要通过定时发送心跳信息来驱动连接状态的变化
|
||||
/// </summary>
|
||||
public bool IsConnected
|
||||
{
|
||||
get
|
||||
{
|
||||
if (this.clientSocket == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return this.clientSocket.Connected;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#endregion
|
||||
|
||||
#region 初始化
|
||||
/// <summary>
|
||||
/// 初始化客户端
|
||||
/// </summary>
|
||||
/// <param name="hostName">服务端地址{IP地址}</param>
|
||||
/// <param name="port">端口号</param>
|
||||
public SocketClient(string hostName, Int32 port)//String hostName, Int32 port
|
||||
{
|
||||
ServerIp = hostName;
|
||||
ServerPort = port.ToString();
|
||||
this.InitHostEndPoint();
|
||||
}
|
||||
/// <summary>
|
||||
/// 初始化HostEndPoint
|
||||
/// </summary>
|
||||
private void InitHostEndPoint()
|
||||
{
|
||||
string hostName = ServerIp;
|
||||
int port = 0;
|
||||
int.TryParse(ServerPort, out port);
|
||||
|
||||
IPAddress address = null;
|
||||
if (!String.IsNullOrEmpty(hostName))
|
||||
{
|
||||
IPAddress.TryParse(hostName, out address);
|
||||
}
|
||||
else
|
||||
{
|
||||
IPHostEntry host = Dns.GetHostEntry("127.0.0.1");
|
||||
IPAddress[] addressList = host.AddressList;
|
||||
foreach (IPAddress ad in addressList)
|
||||
{
|
||||
if (ad.AddressFamily == AddressFamily.InterNetwork)
|
||||
{
|
||||
address = ad;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.hostEndPoint = new IPEndPoint(address, port);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 连接
|
||||
|
||||
/// <summary>
|
||||
/// 连接服务端
|
||||
/// </summary>
|
||||
public void Connect()
|
||||
{
|
||||
bool result = false;
|
||||
this.Disconnect();
|
||||
lock (disPoseLock)
|
||||
{
|
||||
this.clientSocket = new Socket(this.hostEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
|
||||
SocketAsyncEventArgs connectArgs = new SocketAsyncEventArgs();
|
||||
connectArgs.UserToken = this.clientSocket;
|
||||
connectArgs.RemoteEndPoint = this.hostEndPoint;
|
||||
connectArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnConnect);
|
||||
result = clientSocket.ConnectAsync(connectArgs);
|
||||
}//等待连接结果
|
||||
//autoConnectEvent.WaitOne();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 重新连接
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public bool ReConnect()
|
||||
{
|
||||
try
|
||||
{
|
||||
this.Dispose();
|
||||
this.Connect();
|
||||
return this.connected;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<SocketClient>.Error("网络断开:" + ex.Message, ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 没有连接对象返回false,否则重连
|
||||
/// </summary>
|
||||
/// <returns>返回重连结果</returns>
|
||||
public bool IsOrNoReConnect()
|
||||
{
|
||||
try
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
if (this.clientSocket == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return this.ReConnect();
|
||||
}
|
||||
}
|
||||
catch (System.Exception ex)
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<SocketClient>.Error("网络已经断开:" + ex.Message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 连接的完成方法
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void OnConnect(object sender, SocketAsyncEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
//autoConnectEvent.Set();
|
||||
SocketError errorCode = e.SocketError;
|
||||
if (errorCode == SocketError.Success)
|
||||
{
|
||||
listenerSocketAsyncEventArgs = new SocketAsyncEventArgs();
|
||||
byte[] receiveBuffer = new byte[32768];
|
||||
listenerSocketAsyncEventArgs.UserToken = clientSocket;
|
||||
listenerSocketAsyncEventArgs.SetBuffer(receiveBuffer, 0, receiveBuffer.Length);
|
||||
listenerSocketAsyncEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnReceive);
|
||||
StartListenThread += new SocketClient.StartListenHandler(listener_StartListenThread);
|
||||
StartListenThread();
|
||||
}
|
||||
else
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<SocketClient>.Warn(String.Format("连接SocketServer={0}:{1}失败", this.hostEndPoint.Address.ToString(), this.hostEndPoint.Port));
|
||||
//throw new SocketException((Int32)errorCode);
|
||||
e.Dispose();
|
||||
this.Dispose();
|
||||
ConnectFail();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<SocketClient>.Error(ex.Message);
|
||||
}
|
||||
|
||||
this.connected = e.SocketError == SocketError.Success;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 断开连接
|
||||
|
||||
/// <summary>
|
||||
/// 断开连接
|
||||
/// </summary>
|
||||
public void Disconnect()
|
||||
{
|
||||
lock (disPoseLock)
|
||||
{
|
||||
if (clientSocket != null)
|
||||
{
|
||||
if (clientSocket.Connected)
|
||||
{
|
||||
//autoConnectEvent.Close();
|
||||
clientSocket.Shutdown(SocketShutdown.Both);
|
||||
clientSocket.Disconnect(false);
|
||||
}
|
||||
StopListenThread();
|
||||
//ICSharpCode.Core.LoggingService<SocketClient>.Debug("断开连接");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 心跳
|
||||
|
||||
#region 启动心跳时钟
|
||||
|
||||
/// <summary>
|
||||
/// 启动定时器运行服务
|
||||
/// </summary>
|
||||
public void StartHeartbeat()
|
||||
{
|
||||
if (this._timer == null)
|
||||
{
|
||||
this._timer = new System.Timers.Timer();
|
||||
this._timer.Interval = 2000;
|
||||
this._timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
|
||||
this._timer.Start();
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 停止心跳时钟
|
||||
|
||||
/// <summary>
|
||||
/// 停止定时器运行服务
|
||||
/// </summary>
|
||||
public void StopHeartbeat()
|
||||
{
|
||||
if (this._timer != null)
|
||||
{
|
||||
this._timer.Stop();
|
||||
this._timer.Dispose();
|
||||
this._timer = null;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
protected void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
|
||||
{
|
||||
if (this.connected)
|
||||
{
|
||||
//this.Send("0000"); //发送心跳包
|
||||
}
|
||||
else
|
||||
{
|
||||
this.ReConnect(); //重新连接
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 侦听
|
||||
|
||||
private void listener_StartListenThread()
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<SocketClient>.Debug("开始侦听...");
|
||||
//receiveThread = new Thread(new ThreadStart(Listen));
|
||||
Listen();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 停止监听线程
|
||||
/// </summary>
|
||||
public void StopListenThread()
|
||||
{
|
||||
try
|
||||
{
|
||||
this.StopHeartbeat();
|
||||
if (StartListenThread != null)
|
||||
{
|
||||
StartListenThread -= new SocketClient.StartListenHandler(listener_StartListenThread);
|
||||
}
|
||||
if (this.listenerSocketAsyncEventArgs != null)
|
||||
{
|
||||
listenerSocketAsyncEventArgs.Completed -= new EventHandler<SocketAsyncEventArgs>(OnReceive);
|
||||
this.listenerSocketAsyncEventArgs.UserToken = null;
|
||||
this.listenerSocketAsyncEventArgs.Dispose();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<SocketClient>.Error("停止监听线程异常:", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 开始监听线程的入口函数
|
||||
/// </summary>
|
||||
public void Listen()
|
||||
{
|
||||
try
|
||||
{
|
||||
Socket socket = listenerSocketAsyncEventArgs.UserToken as Socket;
|
||||
if (socket != null)
|
||||
{
|
||||
socket.ReceiveAsync(listenerSocketAsyncEventArgs);
|
||||
//if (socket.Connected)
|
||||
//{
|
||||
// this.StartHeartbeat();
|
||||
//}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<SocketClient>.Error("侦听异常!", ex);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 消息
|
||||
|
||||
/// <summary>
|
||||
/// 发送信息
|
||||
/// </summary>
|
||||
/// <param name="message"></param>
|
||||
public bool Send(byte[] sendBuffer)
|
||||
{
|
||||
if (clientSocket != null && this.connected)
|
||||
{
|
||||
SocketAsyncEventArgs senderSocketAsyncEventArgs = new SocketAsyncEventArgs();
|
||||
senderSocketAsyncEventArgs.UserToken = this.clientSocket;
|
||||
senderSocketAsyncEventArgs.SetBuffer(sendBuffer, 0, sendBuffer.Length);
|
||||
senderSocketAsyncEventArgs.RemoteEndPoint = this.hostEndPoint;
|
||||
senderSocketAsyncEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnSend);
|
||||
var result = clientSocket.SendAsync(senderSocketAsyncEventArgs);
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
//throw new SocketException((Int32)SocketError.NotConnected);
|
||||
//ICSharpCode.Core.LoggingService<SocketClient>.Warn("Socket未初始化或未连接!");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 接收的完成方法
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void OnReceive(object sender, SocketAsyncEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (e.BytesTransferred > 0)
|
||||
{
|
||||
byte[] msg = new byte[e.BytesTransferred];
|
||||
Array.Copy(e.Buffer, 0, msg, 0, e.BytesTransferred);
|
||||
//string msg = Encoding.Default.GetString(e.Buffer, 0, e.BytesTransferred);
|
||||
//ICSharpCode.Core.LoggingService<SocketClient>.Debug("接收到数据" + msg);
|
||||
Listen();
|
||||
if (OnMsgReceived != null)
|
||||
OnMsgReceived(msg);
|
||||
}
|
||||
if (e.BytesTransferred==0)
|
||||
{
|
||||
this.connected = false;
|
||||
OnMsgReceived(null);
|
||||
//ICSharpCode.Core.LoggingService<SocketClient>.Debug("server断开连接" + msg);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<SocketClient>.Error("接收数据异常:" + ex.Message, ex);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 发送的完成方法
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void OnSend(object sender, SocketAsyncEventArgs e)
|
||||
{
|
||||
if (e.SocketError == SocketError.Success)
|
||||
{
|
||||
//触发事件
|
||||
if (OnSended != null)
|
||||
{
|
||||
OnSended(true);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
//触发事件
|
||||
if (OnSended != null)
|
||||
{
|
||||
OnSended(false);
|
||||
}
|
||||
this.ProcessError(e);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 处理错误
|
||||
/// </summary>
|
||||
/// <param name="e"></param>
|
||||
private void ProcessError(SocketAsyncEventArgs e)
|
||||
{
|
||||
Socket s = e.UserToken as Socket;
|
||||
if (s != null && s.Connected)
|
||||
{
|
||||
try
|
||||
{
|
||||
s.Shutdown(SocketShutdown.Both);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
//client already closed
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (s.Connected)
|
||||
{
|
||||
s.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
//throw new SocketException((Int32)e.SocketError);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IDisposable Members
|
||||
private object disPoseLock=new object();
|
||||
public void Dispose()
|
||||
{
|
||||
this.Disconnect();
|
||||
lock (disPoseLock)
|
||||
{
|
||||
if (clientSocket != null)
|
||||
{
|
||||
this.clientSocket.Close();
|
||||
this.clientSocket.Dispose();
|
||||
this.clientSocket = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user