新增TCP扩展
This commit is contained in:
1 parent
514d6f5255
commit
f119665d29
26 files changed
+2457
-34
No files matched your search
@@ -0,0 +1,60 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace HHWMS.Web
|
||||
{
|
||||
public sealed class BufferManager : IDisposable
|
||||
{
|
||||
private Byte[] buffer;
|
||||
private Int32 bufferSize;
|
||||
private Int32 numSize;
|
||||
private Int32 currentIndex;
|
||||
private Stack<Int32> freeIndexPool;
|
||||
|
||||
public BufferManager(Int32 numSize, Int32 bufferSize)
|
||||
{
|
||||
this.bufferSize = bufferSize;
|
||||
this.numSize = numSize;
|
||||
this.currentIndex = 0;
|
||||
this.freeIndexPool = new Stack<Int32>();
|
||||
}
|
||||
|
||||
public void FreeBuffer(SocketAsyncEventArgs args)
|
||||
{
|
||||
this.freeIndexPool.Push(args.Offset);
|
||||
args.SetBuffer(null, 0, 0);
|
||||
}
|
||||
|
||||
public void InitBuffer()
|
||||
{
|
||||
this.buffer = new Byte[this.numSize];
|
||||
}
|
||||
|
||||
public Boolean SetBuffer(SocketAsyncEventArgs args)
|
||||
{
|
||||
if (this.freeIndexPool.Count > 0)
|
||||
{
|
||||
args.SetBuffer(this.buffer, this.freeIndexPool.Pop(), this.bufferSize);
|
||||
}
|
||||
else
|
||||
{
|
||||
if ((this.numSize - this.bufferSize) < this.currentIndex)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
args.SetBuffer(this.buffer, this.currentIndex, this.bufferSize);
|
||||
this.currentIndex += this.bufferSize;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
buffer = null;
|
||||
freeIndexPool = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Timers;
|
||||
using HHWMS.Web.Models;
|
||||
using ProtoBuf;
|
||||
namespace HHWMS.Web
|
||||
{
|
||||
public class DevCommuBySocketClient
|
||||
{
|
||||
public enum CommuStatus
|
||||
{
|
||||
OFFLINE = 0,
|
||||
READY = 1,
|
||||
//SENDING = 2,
|
||||
RECEIVING = 3
|
||||
}
|
||||
public const int SendWordLength = 70;
|
||||
//用于通讯的Socket对象
|
||||
private SocketClient _socketClient;
|
||||
public ushort SendIndex { get; set; }
|
||||
public ushort ReadIndex { get; set; }
|
||||
public void ResetComm()
|
||||
{
|
||||
lock (CommuLock)
|
||||
{
|
||||
if (DevCommStatus != CommuStatus.OFFLINE)
|
||||
{
|
||||
DevCommStatus = CommuStatus.READY;
|
||||
}
|
||||
_heartTimer.Stop();
|
||||
_heartTimer.Start();
|
||||
}
|
||||
}
|
||||
public byte[] ExternalSendBuf
|
||||
{
|
||||
set
|
||||
{
|
||||
if (value != null)
|
||||
{
|
||||
lock (CommuLock)
|
||||
{
|
||||
|
||||
externalData = new byte[value.Length];
|
||||
Array.Copy(value, 0, externalData, 0, value.Length);
|
||||
}
|
||||
SendLoop(null, null);
|
||||
_externalSendtimer.Start();
|
||||
}
|
||||
else
|
||||
{
|
||||
lock (CommuLock)
|
||||
{
|
||||
externalData = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//外部触发的需要发送的数据缓存
|
||||
|
||||
public object CommuLock=new object();//通讯锁
|
||||
private System.Timers.Timer _heartTimer;//心跳定时器
|
||||
private System.Timers.Timer _externalSendtimer;//外部缓存发送定时器
|
||||
private int _sendErrCount;//发送失败的次数
|
||||
public CommuStatus DevCommStatus { get; set; }//当前问答模式下的状态
|
||||
|
||||
public delegate void RecMsgHandler(byte[] msg);
|
||||
public event RecMsgHandler RecMsgEvent;
|
||||
|
||||
public delegate void OrderRespHandler();
|
||||
public event OrderRespHandler OrderRespEvent;
|
||||
private int mtime = 0;
|
||||
public DevCommuBySocketClient(string ip, int port, int mtime1)
|
||||
{
|
||||
DevCommStatus = CommuStatus.OFFLINE;
|
||||
_socketClient = new SocketClient(ip, port);
|
||||
_socketClient.StartListenThread += SocketClient_StartListenThread;
|
||||
_socketClient.OnSended += SocketClient_OnSended;
|
||||
_socketClient.OnMsgReceived += SocketClient_OnMsgReceived;
|
||||
_socketClient.ConnectFail += SocketClient_ConnectFail;
|
||||
_socketClient.Connect();
|
||||
|
||||
_heartTimer = new System.Timers.Timer();
|
||||
_heartTimer.Interval = 5000;
|
||||
mtime = mtime1;
|
||||
_heartTimer.Elapsed += new ElapsedEventHandler(HeartBeat);
|
||||
_heartTimer.Start();
|
||||
_externalSendtimer = new System.Timers.Timer
|
||||
{
|
||||
Interval = mtime1
|
||||
};
|
||||
_externalSendtimer.Elapsed += new ElapsedEventHandler(SendLoop);
|
||||
reConCount = 30;
|
||||
SendIndex = 1;
|
||||
|
||||
/*MemoryStream ms = new MemoryStream();
|
||||
MsgInstance msgInstance = new MsgInstance
|
||||
{
|
||||
requestId = "wms1",
|
||||
srctype = MsgInstance.SourceType.HEART_BEAT,
|
||||
|
||||
timeInfo = DateTime.Now.ToString()
|
||||
|
||||
};
|
||||
//序列化 msg
|
||||
Serializer.Serialize(ms, msgInstance);
|
||||
ms.Position = 0;
|
||||
heartBeatData = ms.ToArray();*/
|
||||
}
|
||||
|
||||
private int connectFailCount=0;
|
||||
private void SocketClient_ConnectFail()
|
||||
{
|
||||
connectFailCount++;
|
||||
}
|
||||
|
||||
private uint reConCount;
|
||||
//接收到数据的事件
|
||||
private void SocketClient_OnMsgReceived(byte[] info)
|
||||
{
|
||||
lock (CommuLock)
|
||||
{
|
||||
if (info!=null)
|
||||
{
|
||||
DevCommStatus = CommuStatus.READY;
|
||||
}
|
||||
else
|
||||
{
|
||||
DevCommStatus = CommuStatus.OFFLINE;
|
||||
connectFailCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//发送完成的事件
|
||||
private void SocketClient_OnSended(bool successorfalse)
|
||||
{
|
||||
lock (CommuLock)
|
||||
{
|
||||
if (successorfalse)
|
||||
{
|
||||
externalData = null;
|
||||
DevCommStatus = CommuStatus.READY;
|
||||
}
|
||||
else
|
||||
{
|
||||
DevCommStatus = CommuStatus.OFFLINE;
|
||||
connectFailCount++;
|
||||
_sendErrCount = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//连接设备成功的事件
|
||||
private void SocketClient_StartListenThread()
|
||||
{
|
||||
DevCommStatus = CommuStatus.READY;
|
||||
}
|
||||
|
||||
public bool SendData(byte[] data)
|
||||
{
|
||||
if (DevCommStatus == CommuStatus.READY)
|
||||
{
|
||||
if (_socketClient.Send(data))
|
||||
{
|
||||
//DevCommStatus = CommuStatus.SENDING;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (DevCommStatus== CommuStatus.OFFLINE)
|
||||
{
|
||||
if (connectFailCount!=0)
|
||||
{
|
||||
connectFailCount = 0;
|
||||
_socketClient.Connect();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
bool electry = true;
|
||||
private byte[] heartBeatData;
|
||||
private byte[] externalData;
|
||||
private void HeartBeat(object sender, ElapsedEventArgs e)
|
||||
{
|
||||
lock (CommuLock)
|
||||
{
|
||||
if (electry)
|
||||
{
|
||||
electry = false;
|
||||
_heartTimer.Interval = mtime;
|
||||
}
|
||||
|
||||
if (!_externalSendtimer.Enabled && heartBeatData != null)//没有外部指令的情况下发心跳,优先发外部指令
|
||||
{
|
||||
if (SendData(heartBeatData))
|
||||
{
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
if (++_sendErrCount > reConCount)
|
||||
{
|
||||
_socketClient.ReConnect();
|
||||
_sendErrCount = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void SendLoop(object sender, ElapsedEventArgs e)
|
||||
{
|
||||
lock (CommuLock)
|
||||
{
|
||||
if (externalData != null)
|
||||
{
|
||||
if (SendData(externalData))
|
||||
{
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
if (++_sendErrCount > reConCount)
|
||||
{
|
||||
_socketClient.ReConnect();
|
||||
_sendErrCount = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_externalSendtimer.Stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace HHWMS.Web
|
||||
{
|
||||
public sealed class MySocketAsyncEventArgs : SocketAsyncEventArgs
|
||||
{
|
||||
private string Property; //读写类型
|
||||
|
||||
/// <summary>
|
||||
/// 构造方法
|
||||
/// </summary>
|
||||
/// <param name="property">读写操作类型:Receive/Send</param>
|
||||
public MySocketAsyncEventArgs(string property)
|
||||
{
|
||||
this.Property = property;
|
||||
}
|
||||
/// <summary>
|
||||
/// 用户标识
|
||||
/// </summary>
|
||||
public string UID { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace HHWMS.Web
|
||||
{
|
||||
public class RequestHandler
|
||||
{
|
||||
private string temp = string.Empty;
|
||||
public string[] GetActualString(string input)
|
||||
{
|
||||
return GetActualString(input, null);
|
||||
}
|
||||
private string[] GetActualString(string input, List<string> outputList)
|
||||
{
|
||||
if (outputList == null)
|
||||
outputList = new List<string>();
|
||||
if (!String.IsNullOrEmpty(temp))
|
||||
input = temp + input;
|
||||
string output = "";
|
||||
string pattern = @"(?<=^\[length=)(\d+)(?=\])";
|
||||
int length;
|
||||
if (Regex.IsMatch(input, pattern))
|
||||
{
|
||||
Match m = Regex.Match(input, pattern);
|
||||
length = Convert.ToInt32(m.Groups[0].Value);
|
||||
int startIndex = input.IndexOf(']') + 1;
|
||||
output = input.Substring(startIndex);
|
||||
if (output.Length == length)
|
||||
{
|
||||
outputList.Add(output);
|
||||
temp = "";
|
||||
}
|
||||
else if (output.Length < length)
|
||||
{
|
||||
temp = input;
|
||||
}
|
||||
else if (output.Length > length)
|
||||
{
|
||||
output = output.Substring(0, length);
|
||||
outputList.Add(output);
|
||||
temp = "";
|
||||
input = input.Substring(startIndex + length);
|
||||
GetActualString(input, outputList);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
temp = input;
|
||||
outputList.Add(temp);
|
||||
}
|
||||
return outputList.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.IO.Ports;
|
||||
|
||||
namespace HHWMS.Web
|
||||
{
|
||||
/// <summary>
|
||||
/// 串口通讯服务类
|
||||
/// </summary>
|
||||
public class SerialPortService
|
||||
{
|
||||
#region 单例实现
|
||||
|
||||
//private static SerialPortService instance = null;
|
||||
//private Dictionary<int, SerialPort> _dicSerialPort = null; //保存串口对象的集合
|
||||
|
||||
//private SerialPortService()
|
||||
//{
|
||||
// if (this._dicSerialPort == null)
|
||||
// {
|
||||
// this._dicSerialPort = new Dictionary<int, SerialPort>();
|
||||
// }
|
||||
//}
|
||||
|
||||
//public static SerialPortService Instance
|
||||
//{
|
||||
// get
|
||||
// {
|
||||
// if (instance == null)
|
||||
// {
|
||||
// instance = new SerialPortService();
|
||||
// }
|
||||
// return instance;
|
||||
// }
|
||||
//}
|
||||
|
||||
//#endregion
|
||||
|
||||
//#region 获取串口对象
|
||||
|
||||
///// <summary>
|
||||
///// 获取串口对象
|
||||
///// </summary>
|
||||
///// <param name="portName">串口名称</param>
|
||||
///// <param name="baudRate">波特率</param>
|
||||
///// <returns>返可用的串口对象</returns>
|
||||
//public SerialPort GetSerialPort(string portName, int baudRate)
|
||||
//{
|
||||
// SerialPort currSerialPort = null;
|
||||
// foreach (SerialPort sp in this._dicSerialPort.Values)
|
||||
// {
|
||||
// if (sp.PortName == portName && sp.BaudRate == baudRate)
|
||||
// {
|
||||
// currSerialPort = sp;
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// if (currSerialPort == null)
|
||||
// {
|
||||
// currSerialPort = new SerialPort();
|
||||
// currSerialPort.PortName = portName;
|
||||
// currSerialPort.BaudRate = baudRate;
|
||||
|
||||
// currSerialPort.ReadTimeout = 3000;
|
||||
// currSerialPort.Handshake = Handshake.None;
|
||||
// currSerialPort.ReceivedBytesThreshold = 1;
|
||||
|
||||
// currSerialPort.RtsEnable = true;
|
||||
|
||||
// currSerialPort.Encoding = System.Text.Encoding.Default;
|
||||
// this._dicSerialPort.Add(currSerialPort.GetHashCode(), currSerialPort);
|
||||
// }
|
||||
// try
|
||||
// {
|
||||
// if (currSerialPort.IsOpen)
|
||||
// {
|
||||
// currSerialPort.Close();
|
||||
// currSerialPort.Open();
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// currSerialPort.Open();
|
||||
// }
|
||||
// }
|
||||
// catch (Exception ex)
|
||||
// {
|
||||
// //ICSharpCode.Core.LoggingService.Warn(String.Format("串口{0}关闭或打开失败,重新创建串口对象,详情:{1}", portName, ex.Message));
|
||||
// this._dicSerialPort.Remove(currSerialPort.GetHashCode());
|
||||
// currSerialPort = new SerialPort();
|
||||
// currSerialPort.PortName = portName;
|
||||
// currSerialPort.BaudRate = baudRate;
|
||||
|
||||
// currSerialPort.ReadTimeout = 3000;
|
||||
// currSerialPort.Handshake = Handshake.None;
|
||||
// currSerialPort.ReceivedBytesThreshold = 1;
|
||||
// currSerialPort.RtsEnable = true;
|
||||
|
||||
// currSerialPort.Encoding = System.Text.Encoding.Default;
|
||||
// this._dicSerialPort.Add(currSerialPort.GetHashCode(), currSerialPort);
|
||||
// currSerialPort.Open();
|
||||
// }
|
||||
// return currSerialPort;
|
||||
//}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace HHWMS.Web
|
||||
{
|
||||
public enum ServerState { Initialing, Inited, Ready, Running, Stoped }
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace HHWMS.Web
|
||||
{
|
||||
public sealed class SocketAsyncEventArgsPool : IDisposable
|
||||
{
|
||||
private Stack<SocketAsyncEventArgsWithId> pool;
|
||||
private IDictionary<string, SocketAsyncEventArgsWithId> busypool;
|
||||
//private string[] keys;
|
||||
|
||||
public Int32 Count
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (this.pool)
|
||||
{
|
||||
return this.pool.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public string[] OnlineUID
|
||||
{
|
||||
get
|
||||
{
|
||||
string[] keys = null;
|
||||
lock (this.busypool)
|
||||
{
|
||||
//busypool.Keys.CopyTo(keys, 0);
|
||||
keys = busypool.Keys.ToArray<string>();
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
}
|
||||
|
||||
public Stack<SocketAsyncEventArgsWithId> Pool { get { return this.pool; } }
|
||||
|
||||
public IDictionary<string, SocketAsyncEventArgsWithId> BusyPool { get { return this.busypool; } }
|
||||
|
||||
public SocketAsyncEventArgsPool(Int32 capacity)
|
||||
{
|
||||
//keys = new string[capacity];
|
||||
this.pool = new Stack<SocketAsyncEventArgsWithId>(capacity);
|
||||
this.busypool = new Dictionary<string, SocketAsyncEventArgsWithId>(capacity);
|
||||
}
|
||||
|
||||
public SocketAsyncEventArgsWithId Pop(string uid)
|
||||
{
|
||||
if (uid == string.Empty || uid == "")
|
||||
return null;
|
||||
SocketAsyncEventArgsWithId si = null;
|
||||
lock (this.pool)
|
||||
{
|
||||
si = this.pool.Pop();
|
||||
}
|
||||
si.UID = uid;
|
||||
si.State = true; //mark the state of pool is not the initial step
|
||||
busypool.Add(uid, si);
|
||||
return si;
|
||||
}
|
||||
|
||||
public void Push(SocketAsyncEventArgsWithId item)
|
||||
{
|
||||
if (item == null)
|
||||
throw new ArgumentNullException("SocketAsyncEventArgsWithId对象为空");
|
||||
if (item.State == true)
|
||||
{
|
||||
if (busypool.Keys.Count != 0)
|
||||
{
|
||||
if (busypool.Keys.Contains(item.UID))
|
||||
busypool.Remove(item.UID);
|
||||
//else
|
||||
// throw new ArgumentException("SocketAsyncEventWithId不在忙碌队列中");
|
||||
}
|
||||
else
|
||||
throw new ArgumentException("忙碌队列为空");
|
||||
}
|
||||
item.UID = "-1";
|
||||
item.State = false;
|
||||
lock (this.pool)
|
||||
{
|
||||
this.pool.Push(item);
|
||||
}
|
||||
}
|
||||
|
||||
public SocketAsyncEventArgsWithId FindByUID(string uid)
|
||||
{
|
||||
if (uid == string.Empty || uid == "")
|
||||
return null;
|
||||
SocketAsyncEventArgsWithId si = null;
|
||||
foreach (string key in this.OnlineUID)
|
||||
{
|
||||
if (key == uid)
|
||||
{
|
||||
si = busypool[uid];
|
||||
break;
|
||||
}
|
||||
}
|
||||
return si;
|
||||
}
|
||||
|
||||
public bool BusyPoolContains(string uid)
|
||||
{
|
||||
lock (this.busypool)
|
||||
{
|
||||
return busypool.Keys.Contains(uid);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
this.pool.Clear();
|
||||
this.busypool.Clear();
|
||||
this.pool = null;
|
||||
this.busypool = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace HHWMS.Web
|
||||
{
|
||||
public sealed class SocketAsyncEventArgsWithId : IDisposable
|
||||
{
|
||||
private string uid = "-1";
|
||||
private bool state = false;
|
||||
private bool isAllowReceive = true;
|
||||
private MySocketAsyncEventArgs receiveSaea;
|
||||
private MySocketAsyncEventArgs sendSaea;
|
||||
|
||||
public SocketAsyncEventArgsWithId()
|
||||
{
|
||||
this.receiveSaea = new MySocketAsyncEventArgs("Receive");
|
||||
this.sendSaea = new MySocketAsyncEventArgs("Send");
|
||||
}
|
||||
|
||||
public string UID
|
||||
{
|
||||
get { return uid; }
|
||||
set
|
||||
{
|
||||
uid = value;
|
||||
receiveSaea.UID = value;
|
||||
sendSaea.UID = value;
|
||||
}
|
||||
}
|
||||
|
||||
public bool State
|
||||
{
|
||||
get { return this.state; }
|
||||
set { this.state = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 是否允许接收
|
||||
/// </summary>
|
||||
public bool IsAllowReceive
|
||||
{
|
||||
get { return this.isAllowReceive; }
|
||||
set { this.isAllowReceive = value; }
|
||||
}
|
||||
|
||||
public MySocketAsyncEventArgs ReceiveSAEA
|
||||
{
|
||||
get { return this.receiveSaea; }
|
||||
set { this.receiveSaea = value; }
|
||||
}
|
||||
|
||||
public MySocketAsyncEventArgs SendSAEA
|
||||
{
|
||||
get { return this.sendSaea; }
|
||||
set { this.sendSaea = value; }
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
this.receiveSaea.Dispose();
|
||||
this.sendSaea.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,696 @@
|
||||
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
|
||||
{
|
||||
public sealed class SocketListener : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// 缓冲区
|
||||
/// </summary>
|
||||
private BufferManager bufferManager;
|
||||
/// <summary>
|
||||
/// 服务器端Socket
|
||||
/// </summary>
|
||||
private Socket listenSocket;
|
||||
/// <summary>
|
||||
/// 服务同步锁
|
||||
/// </summary>
|
||||
private Mutex mutex;
|
||||
/// <summary>
|
||||
/// 当前连接数
|
||||
/// </summary>
|
||||
private Int32 numConnections;
|
||||
/// <summary>
|
||||
/// 最大并发量
|
||||
/// </summary>
|
||||
private Int32 numConcurrence;
|
||||
/// <summary>
|
||||
/// 服务器状态
|
||||
/// </summary>
|
||||
private ServerState serverstate;
|
||||
/// <summary>
|
||||
/// 读取写入字节
|
||||
/// </summary>
|
||||
private const Int32 opsToPreAlloc = 1;
|
||||
/// <summary>
|
||||
/// Socket连接池
|
||||
/// </summary>
|
||||
private SocketAsyncEventArgsPool readWritePool;
|
||||
/// <summary>
|
||||
/// 并发控制信号量
|
||||
/// </summary>
|
||||
private Semaphore semaphoreAcceptedClients;
|
||||
/// <summary>
|
||||
/// 通信协议
|
||||
/// </summary>
|
||||
private RequestHandler handler;
|
||||
/// <summary>
|
||||
/// 回调委托
|
||||
/// </summary>
|
||||
/// <param name="IP"></param>
|
||||
/// <returns></returns>
|
||||
public delegate string GetIDByIPFun(string IP);
|
||||
/// <summary>
|
||||
/// 回调方法实例
|
||||
/// </summary>
|
||||
private GetIDByIPFun GetIDByIP;
|
||||
/// <summary>
|
||||
/// 接收到信息时的事件委托
|
||||
/// </summary>
|
||||
/// <param name="info"></param>
|
||||
public delegate void ReceiveMsgHandler(string uid, byte[] info);
|
||||
/// <summary>
|
||||
/// 接收到信息时的事件
|
||||
/// </summary>
|
||||
public event ReceiveMsgHandler OnMsgReceived;
|
||||
/// <summary>
|
||||
/// 客户端关闭连接时的委托
|
||||
/// </summary>
|
||||
/// <param name="uid"></param>
|
||||
public delegate void ClientClose(string uid);
|
||||
/// <summary>
|
||||
/// 客户端关闭连接时的事件
|
||||
/// </summary>
|
||||
public event ClientClose OnClientClose;
|
||||
/// <summary>
|
||||
/// 开始监听数据的委托
|
||||
/// </summary>
|
||||
public delegate void StartListenHandler();
|
||||
/// <summary>
|
||||
/// 开始监听数据的事件
|
||||
/// </summary>
|
||||
public event StartListenHandler StartListenThread;
|
||||
/// <summary>
|
||||
/// 发送信息完成后的委托
|
||||
/// </summary>
|
||||
/// <param name="successorfalse"></param>
|
||||
public delegate void SendCompletedHandler(string uid, string exception);
|
||||
/// <summary>
|
||||
/// 发送信息完成后的事件
|
||||
/// </summary>
|
||||
public event SendCompletedHandler OnSended;
|
||||
|
||||
private bool listenFlag = false;
|
||||
|
||||
public bool ListenFlag { get { return this.listenFlag; } set { this.listenFlag= value; } }
|
||||
|
||||
/// <summary>
|
||||
/// 获取当前的并发数
|
||||
/// </summary>
|
||||
public Int32 NumConnections
|
||||
{
|
||||
get { return this.numConnections; }
|
||||
}
|
||||
/// <summary>
|
||||
/// 最大并发数
|
||||
/// </summary>
|
||||
public Int32 MaxConcurrence
|
||||
{
|
||||
get { return this.numConcurrence; }
|
||||
}
|
||||
/// <summary>
|
||||
/// 返回服务器状态
|
||||
/// </summary>
|
||||
public ServerState State
|
||||
{
|
||||
get
|
||||
{
|
||||
return serverstate;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取当前在线用户的UID
|
||||
/// </summary>
|
||||
public string[] OnlineUID
|
||||
{
|
||||
get { return readWritePool.OnlineUID; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 初始化服务器端
|
||||
/// </summary>
|
||||
/// <param name="numConcurrence">并发的连接数量(1000以上)</param>
|
||||
/// <param name="receiveBufferSize">每一个收发缓冲区的大小(32768)</param>
|
||||
public SocketListener(Int32 numConcurrence, Int32 receiveBufferSize, GetIDByIPFun GetIDByIP)
|
||||
{
|
||||
try
|
||||
{
|
||||
this.mutex = new Mutex();
|
||||
|
||||
serverstate = ServerState.Initialing;
|
||||
this.numConnections = 0;
|
||||
this.numConcurrence = numConcurrence;
|
||||
this.bufferManager = new BufferManager(receiveBufferSize * numConcurrence * opsToPreAlloc, receiveBufferSize);
|
||||
this.readWritePool = new SocketAsyncEventArgsPool(numConcurrence);
|
||||
this.semaphoreAcceptedClients = new Semaphore(numConcurrence, numConcurrence);
|
||||
handler = new RequestHandler();
|
||||
this.GetIDByIP = GetIDByIP;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<SocketListener>.Error("SocketListener错误:" + ex.Message, ex);
|
||||
//ICSharpCode.Core.LoggingService<SocketListener>.Error(ex.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 服务端初始化
|
||||
/// </summary>
|
||||
public void Init()
|
||||
{
|
||||
try
|
||||
{
|
||||
this.bufferManager.InitBuffer();
|
||||
SocketAsyncEventArgsWithId readWriteEventArgWithId;
|
||||
for (Int32 i = 0; i < this.numConcurrence; i++)
|
||||
{
|
||||
readWriteEventArgWithId = new SocketAsyncEventArgsWithId();
|
||||
|
||||
readWriteEventArgWithId.SendSAEA.Completed += new EventHandler<SocketAsyncEventArgs>(OnSendCompleted);
|
||||
readWriteEventArgWithId.ReceiveSAEA.Completed += new EventHandler<SocketAsyncEventArgs>(OnReceiveCompleted);
|
||||
//只给接收的SocketAsyncEventArgs设置缓冲区
|
||||
this.bufferManager.SetBuffer(readWriteEventArgWithId.ReceiveSAEA);
|
||||
this.readWritePool.Push(readWriteEventArgWithId);
|
||||
}
|
||||
serverstate = ServerState.Inited;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<SocketListener>.Error("ScoketListner Init错误:" + ex.Message, ex);
|
||||
//ICSharpCode.Core.LoggingService<SocketListener>.Error(ex.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 启动服务器
|
||||
/// </summary>
|
||||
/// <param name="data">端口号</param>
|
||||
public void Start(string ip, Object data)
|
||||
{
|
||||
try
|
||||
{
|
||||
Int32 port = (Int32)data;
|
||||
IPAddress[] addresslist = Dns.GetHostEntry(Environment.MachineName).AddressList;
|
||||
IPAddress ipAddress = addresslist[addresslist.Length - 1];
|
||||
if (ip != null)
|
||||
{
|
||||
IPAddress.TryParse(ip.ToString(), out ipAddress);
|
||||
}
|
||||
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
|
||||
this.listenSocket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
|
||||
if (localEndPoint.AddressFamily == AddressFamily.InterNetworkV6)
|
||||
{
|
||||
this.listenSocket.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, false);
|
||||
this.listenSocket.Bind(new IPEndPoint(IPAddress.IPv6Any, localEndPoint.Port));
|
||||
}
|
||||
else
|
||||
{
|
||||
this.listenSocket.Bind(localEndPoint);
|
||||
}
|
||||
this.listenSocket.Listen(100);
|
||||
this.StartAccept(null);
|
||||
//开始监听已连接用户的发送数据
|
||||
if (StartListenThread != null)
|
||||
{
|
||||
StartListenThread();
|
||||
}
|
||||
serverstate = ServerState.Running;
|
||||
|
||||
mutex.WaitOne();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<SocketListener>.Error("SocketListner Start错误:" + ex.Message, ex);
|
||||
//ICSharpCode.Core.LoggingService<SocketListener>.Error(ex.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 开始监听线程的入口函数
|
||||
/// </summary>
|
||||
public void Listen()
|
||||
{
|
||||
|
||||
while (this.listenFlag)
|
||||
{
|
||||
lock (readWritePool)
|
||||
{
|
||||
string currUser = String.Empty;
|
||||
try
|
||||
{
|
||||
string[] keys = readWritePool.OnlineUID;
|
||||
foreach (string uid in keys)
|
||||
{
|
||||
currUser = uid;
|
||||
|
||||
if (uid != null && readWritePool.BusyPool.ContainsKey(uid) && readWritePool.BusyPool[uid] != null)
|
||||
{
|
||||
SocketAsyncEventArgsWithId sawd = readWritePool.BusyPool[uid];
|
||||
if (sawd != null || sawd.ReceiveSAEA == null)
|
||||
{
|
||||
if (readWritePool.BusyPool[uid].ReceiveSAEA.UID == null)
|
||||
{
|
||||
readWritePool.BusyPool[uid].ReceiveSAEA.UID = uid;
|
||||
}
|
||||
if ((readWritePool.BusyPool[uid].ReceiveSAEA.UserToken as Socket).Available > 0)// readWritePool.BusyPool[uid].ReceiveSAEA.LastOperation != SocketAsyncOperation.Receive)
|
||||
{
|
||||
Boolean willRaiseEvent = (readWritePool.BusyPool[uid].ReceiveSAEA.UserToken as Socket).ReceiveAsync(readWritePool.BusyPool[uid].ReceiveSAEA);
|
||||
if (!willRaiseEvent)
|
||||
ProcessReceive(readWritePool.BusyPool[uid].ReceiveSAEA);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
readWritePool.BusyPool.Remove(uid);
|
||||
}
|
||||
#region 注释
|
||||
//else if (readWritePool.BusyPool[uid].ReceiveSAEA.LastOperation == SocketAsyncOperation.None)
|
||||
//{
|
||||
// //以下为心跳处理
|
||||
// Boolean willRaiseEvent = (readWritePool.BusyPool[uid].ReceiveSAEA.UserToken as Socket).ReceiveAsync(readWritePool.BusyPool[uid].ReceiveSAEA);
|
||||
//}
|
||||
//else if (readWritePool.BusyPool[uid].ReceiveSAEA.LastOperation == SocketAsyncOperation.Receive && readWritePool.BusyPool[uid].ReceiveSAEA.SocketError == SocketError.Success)
|
||||
//{
|
||||
// try
|
||||
// {
|
||||
// try
|
||||
// {
|
||||
// lock (String.Empty)
|
||||
// {
|
||||
// if (readWritePool.BusyPool[uid].IsAllowReceive)
|
||||
// {
|
||||
// //以下为心跳处理
|
||||
// Boolean willRaiseEvent = (readWritePool.BusyPool[uid].ReceiveSAEA.UserToken as Socket).ReceiveAsync(readWritePool.BusyPool[uid].ReceiveSAEA);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// catch (System.InvalidOperationException ex)
|
||||
// {
|
||||
// ////ICSharpCode.Core.LoggingService.Error("心跳处理报错无效操作:" + ex.Message);
|
||||
// //如果产生无效操作异常,说明正常连接,正在接收数据,停止心跳包发送数据
|
||||
// if (readWritePool.BusyPool.ContainsKey(uid))
|
||||
// {
|
||||
// readWritePool.BusyPool[uid].IsAllowReceive = false;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// catch (Exception ex)
|
||||
// {
|
||||
// //ICSharpCode.Core.LoggingService.Error("心跳处理报错:" + ex.Message);
|
||||
// //ICSharpCode.Core.LoggingService.Error(ex.StackTrace);
|
||||
// if (readWritePool.BusyPool.ContainsKey(uid))
|
||||
// {
|
||||
// readWritePool.BusyPool[uid].IsAllowReceive = false;
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
#endregion
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<SocketListener>.Error("监听错误:" + ex.Message, ex);
|
||||
////ICSharpCode.Core.LoggingService.Error(ex.StackTrace);
|
||||
try
|
||||
{
|
||||
if (readWritePool.BusyPool.ContainsKey(currUser) && readWritePool.BusyPool[currUser] != null)
|
||||
{
|
||||
readWritePool.BusyPool[currUser].Dispose();
|
||||
readWritePool.BusyPool.Remove(currUser);
|
||||
}
|
||||
else
|
||||
{
|
||||
readWritePool.BusyPool.Remove(currUser);
|
||||
}
|
||||
Interlocked.Decrement(ref this.numConnections);
|
||||
//ICSharpCode.Core.LoggingService<SocketListener>.Debug("当前连接数:" + this.numConnections);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
Thread.Sleep(1000);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发送信息
|
||||
/// </summary>
|
||||
/// <param name="uid">要发送的用户的uid</param>
|
||||
/// <param name="msg">消息体</param>
|
||||
public void Send(string uid, string msg)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
||||
if (uid == string.Empty || uid == "" || msg == string.Empty || msg == "")
|
||||
return;
|
||||
SocketAsyncEventArgsWithId socketWithId = readWritePool.FindByUID(uid);
|
||||
if (socketWithId == null)
|
||||
//说明用户已经断开
|
||||
//100 发送成功
|
||||
//200 发送失败
|
||||
//300 用户不在线
|
||||
//其它 表示异常的信息
|
||||
OnSended(uid, "300");
|
||||
else
|
||||
{
|
||||
MySocketAsyncEventArgs e = socketWithId.SendSAEA;
|
||||
if (e.SocketError == SocketError.Success)
|
||||
{
|
||||
try
|
||||
{
|
||||
lock (String.Empty)
|
||||
{
|
||||
//string message = @"[lenght=" + msg.Length + @"]" + msg;
|
||||
string message = msg;
|
||||
byte[] sendbuffer = System.Text.Encoding.Default.GetBytes(message);
|
||||
//e.SetBuffer(sendbuffer, 0, sendbuffer.Length);
|
||||
(e.UserToken as Socket).Send(sendbuffer);
|
||||
//Boolean willRaiseEvent = (e.UserToken as Socket).SendAsync(e);
|
||||
//if (!willRaiseEvent)
|
||||
//{
|
||||
// this.ProcessSend(e);
|
||||
//}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
////ICSharpCode.Core.LoggingService.Error("Send错误:" + ex.Message, ex);
|
||||
//if (i <= 5)
|
||||
//{
|
||||
// i++;
|
||||
// //如果发送出现异常就延迟0.01秒再发
|
||||
// Thread.Sleep(10);
|
||||
// Send(uid, msg);
|
||||
//}
|
||||
//else
|
||||
//{
|
||||
// OnSended(uid, ex.ToString());
|
||||
//}
|
||||
OnSended(uid, ex.ToString());
|
||||
this.CloseClientSocket(((MySocketAsyncEventArgs)e).UID);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
OnSended(uid, "200");
|
||||
this.CloseClientSocket(((MySocketAsyncEventArgs)e).UID);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<SocketListener>.Error("Send错误:" + ex.Message, ex);
|
||||
//ICSharpCode.Core.LoggingService<SocketListener>.Error(ex.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 停止服务器
|
||||
/// </summary>
|
||||
public void Stop()
|
||||
{
|
||||
try
|
||||
{
|
||||
this.listenFlag = false;
|
||||
if (listenSocket != null)
|
||||
listenSocket.Close();
|
||||
listenSocket = null;
|
||||
Dispose();
|
||||
try
|
||||
{
|
||||
mutex.ReleaseMutex();
|
||||
}
|
||||
catch (ApplicationException ae)
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<SocketListener>.Error(ae.Message);
|
||||
}
|
||||
serverstate = ServerState.Stoped;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<SocketListener>.Error("SocketListner Stop错误:" + ex.Message, ex);
|
||||
//ICSharpCode.Core.LoggingService<SocketListener>.Error(ex.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void StartAccept(SocketAsyncEventArgs acceptEventArg)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (acceptEventArg == null)
|
||||
{
|
||||
acceptEventArg = new SocketAsyncEventArgs();
|
||||
acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(OnAcceptCompleted);
|
||||
}
|
||||
else
|
||||
acceptEventArg.AcceptSocket = null;
|
||||
this.semaphoreAcceptedClients.WaitOne();
|
||||
Boolean willRaiseEvent = this.listenSocket.AcceptAsync(acceptEventArg);
|
||||
if (!willRaiseEvent)
|
||||
{
|
||||
this.ProcessAccept(acceptEventArg);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<SocketListener>.Error("SocketListener StartAccept错误:" + ex.Message, ex);
|
||||
//ICSharpCode.Core.LoggingService<SocketListener>.Error(ex.StackTrace);
|
||||
}
|
||||
}
|
||||
private void OnAcceptCompleted(object sender, SocketAsyncEventArgs e)
|
||||
{
|
||||
this.ProcessAccept(e);
|
||||
}
|
||||
private void ProcessAccept(SocketAsyncEventArgs e)
|
||||
{
|
||||
if (readWritePool != null)
|
||||
{
|
||||
lock (readWritePool)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (e.LastOperation != SocketAsyncOperation.Accept) //检查上一次操作是否是Accept,不是就返回
|
||||
return;
|
||||
if (this.State == ServerState.Stoped) return;
|
||||
if (e.AcceptSocket.RemoteEndPoint == null) //服务器断开连接
|
||||
return;
|
||||
IPEndPoint ipEndPoint = e.AcceptSocket.RemoteEndPoint as IPEndPoint;
|
||||
string UID = GetIDByIP(ipEndPoint.Address.ToString() + ":" + ipEndPoint.Port); //根据IP获取用户的UID
|
||||
if (UID == string.Empty || UID == null || UID == "")
|
||||
return;
|
||||
if (readWritePool.BusyPoolContains(UID)) //判断现在的用户是否已经连接,避免同一用户开两个连接
|
||||
{
|
||||
this.CloseClientSocket(UID);
|
||||
return;
|
||||
}
|
||||
SocketAsyncEventArgsWithId readEventArgsWithId = this.readWritePool.Pop(UID);
|
||||
|
||||
if (readEventArgsWithId.ReceiveSAEA.SocketError != SocketError.Success && readEventArgsWithId.ReceiveSAEA.SocketError != SocketError.ConnectionReset)
|
||||
{
|
||||
readEventArgsWithId.ReceiveSAEA.UserToken = null;
|
||||
readEventArgsWithId.ReceiveSAEA.Dispose();
|
||||
readEventArgsWithId.ReceiveSAEA = new MySocketAsyncEventArgs("Receive");
|
||||
readEventArgsWithId.ReceiveSAEA.Completed += new EventHandler<SocketAsyncEventArgs>(OnReceiveCompleted);
|
||||
|
||||
}
|
||||
if (readEventArgsWithId.SendSAEA.SocketError != SocketError.Success && readEventArgsWithId.SendSAEA.SocketError != SocketError.ConnectionReset)
|
||||
{
|
||||
readEventArgsWithId.SendSAEA.UserToken = null;
|
||||
readEventArgsWithId.SendSAEA.Dispose();
|
||||
readEventArgsWithId.SendSAEA = new MySocketAsyncEventArgs("Send");
|
||||
readEventArgsWithId.SendSAEA.Completed += new EventHandler<SocketAsyncEventArgs>(OnSendCompleted);
|
||||
}
|
||||
|
||||
readEventArgsWithId.ReceiveSAEA.UserToken = e.AcceptSocket;
|
||||
readEventArgsWithId.SendSAEA.UserToken = e.AcceptSocket;
|
||||
readEventArgsWithId.IsAllowReceive = true;
|
||||
Interlocked.Increment(ref this.numConnections);
|
||||
//Console.WriteLine("当前连接:" + this.numConnections);
|
||||
//ICSharpCode.Core.LoggingService<SocketListener>.Debug("当前连接数:" + this.numConnections);
|
||||
//触发处理客户端连接完成事件
|
||||
if (this.ProcessAcceptComplete != null)
|
||||
{
|
||||
this.ProcessAcceptComplete(UID, e);
|
||||
}
|
||||
this.StartAccept(e);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<SocketListener>.Error("ProcessAccept错误:" + ex.Message, ex);
|
||||
//ICSharpCode.Core.LoggingService<SocketListener>.Error(ex.StackTrace);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void OnReceiveCompleted(object sender, SocketAsyncEventArgs e)
|
||||
{
|
||||
ProcessReceive(e);
|
||||
}
|
||||
private void OnSendCompleted(object sender, SocketAsyncEventArgs e)
|
||||
{
|
||||
////ICSharpCode.Core.LoggingService.Debug("操作类型:" + e.LastOperation);
|
||||
ProcessSend(e);
|
||||
}
|
||||
private void ProcessReceive(SocketAsyncEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
lock (String.Empty)
|
||||
{
|
||||
if (e.LastOperation != SocketAsyncOperation.Receive)
|
||||
return;
|
||||
// 检查如果远程主机关闭了连接
|
||||
if (e.BytesTransferred > 0)
|
||||
{
|
||||
if (e.SocketError == SocketError.Success)
|
||||
{
|
||||
Int32 byteTransferred = e.BytesTransferred;
|
||||
string received = System.Text.Encoding.Default.GetString(e.Buffer, e.Offset, byteTransferred);
|
||||
byte[] data = new byte[byteTransferred];
|
||||
Array.Copy(e.Buffer, e.Offset, data, 0, byteTransferred);
|
||||
OnMsgReceived(((MySocketAsyncEventArgs)e).UID, data) ;
|
||||
//检查消息的准确性
|
||||
//string[] msg = handler.GetActualString(received);
|
||||
//foreach (string m in msg)
|
||||
// OnMsgReceived(((MySocketAsyncEventArgs)e).UID, m);
|
||||
try
|
||||
{
|
||||
//可以在这里设一个停顿来实现间隔时间段监听,这里的停顿是单个用户间的监听间隔
|
||||
//发送一个异步接受请求,并获取请求是否为成功
|
||||
Boolean willRaiseEvent = (e.UserToken as Socket).ReceiveAsync(e);
|
||||
if (!willRaiseEvent)
|
||||
ProcessReceive(e);
|
||||
}
|
||||
catch (System.InvalidOperationException ex)
|
||||
{
|
||||
//ProcessReceive(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
this.CloseClientSocket(((MySocketAsyncEventArgs)e).UID);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<SocketListener>.Error("ProcessReceive错误:" + ex.Message, ex);
|
||||
////ICSharpCode.Core.LoggingService<SocketListener>.Error(ex.StackTrace);
|
||||
}
|
||||
}
|
||||
private void ProcessSend(SocketAsyncEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 检查如果远程主机关闭了连接
|
||||
if (e.SocketError == SocketError.Success)
|
||||
{
|
||||
if (e.LastOperation != SocketAsyncOperation.Send)
|
||||
return;
|
||||
if (e.BytesTransferred > 0)
|
||||
{
|
||||
if (e.SocketError == SocketError.Success)
|
||||
OnSended(((MySocketAsyncEventArgs)e).UID, "100");
|
||||
else
|
||||
OnSended(((MySocketAsyncEventArgs)e).UID, "200");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
this.CloseClientSocket(((MySocketAsyncEventArgs)e).UID);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<SocketListener>.Error("ProcessSend错误:" + ex.Message, ex);
|
||||
////ICSharpCode.Core.LoggingService<SocketListener>.Error(ex.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
private void CloseClientSocket(string uid)
|
||||
{
|
||||
if (readWritePool != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (uid == string.Empty || uid == "")
|
||||
return;
|
||||
SocketAsyncEventArgsWithId saeaw = readWritePool.FindByUID(uid);
|
||||
if (saeaw == null)
|
||||
return;
|
||||
Socket s = saeaw.ReceiveSAEA.UserToken as Socket;
|
||||
try
|
||||
{
|
||||
s.Shutdown(SocketShutdown.Both);
|
||||
saeaw.ReceiveSAEA.DisconnectReuseSocket = true;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
//客户端已经关闭
|
||||
//Console.WriteLine("客户端已经关闭!");
|
||||
//ICSharpCode.Core.LoggingService<SocketListener>.Warn("客户端已经关闭!");
|
||||
}
|
||||
this.semaphoreAcceptedClients.Release();
|
||||
Interlocked.Decrement(ref this.numConnections);
|
||||
this.readWritePool.Push(saeaw);
|
||||
//出发事件
|
||||
if (this.OnClientClose != null)
|
||||
{
|
||||
this.OnClientClose(uid);
|
||||
}
|
||||
//Console.WriteLine("当前连接数:" + this.numConnections);
|
||||
//ICSharpCode.Core.LoggingService<SocketListener>.Debug("当前连接数:" + this.numConnections);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<SocketListener>.Error("CloseClientSocket错误:" + ex.Message, ex);
|
||||
////ICSharpCode.Core.LoggingService.Error(ex.StackTrace);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#region IDisposable Members
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (bufferManager != null)
|
||||
{
|
||||
bufferManager.Dispose();
|
||||
bufferManager = null;
|
||||
}
|
||||
if (readWritePool != null)
|
||||
{
|
||||
readWritePool.Dispose();
|
||||
readWritePool = null;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<SocketListener>.Error("Dispose错误:" + ex.Message, ex);
|
||||
//ICSharpCode.Core.LoggingService<SocketListener>.Error(ex.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// 处理接收客户端连接完成事件
|
||||
/// </summary>
|
||||
public event EventHandler<SocketAsyncEventArgs> ProcessAcceptComplete;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
|
||||
namespace HHWMS.Web
|
||||
{
|
||||
public class SyncSocketClient
|
||||
{
|
||||
private static SyncSocketClient instance = null;
|
||||
/// <summary>
|
||||
/// 客户端连接Socket
|
||||
/// </summary>
|
||||
private Socket clientSocket;
|
||||
/// <summary>
|
||||
/// 连接点
|
||||
/// </summary>
|
||||
private IPEndPoint hostEndPoint;
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="hostName">服务端地址{IP地址}</param>
|
||||
/// <param name="port">端口号</param>
|
||||
public SyncSocketClient(String hostName, Int32 port)
|
||||
{
|
||||
//IPAddress address = null;
|
||||
//if (!String.IsNullOrEmpty(hostName))
|
||||
//{
|
||||
// IPAddress.TryParse(hostName, out address);
|
||||
//}
|
||||
//else
|
||||
//{
|
||||
// IPHostEntry host = Dns.GetHostEntry(hostName);
|
||||
// IPAddress[] addressList = host.AddressList;
|
||||
// foreach (IPAddress ad in addressList)
|
||||
// {
|
||||
// if (ad.AddressFamily == AddressFamily.InterNetwork)
|
||||
// {
|
||||
// address = ad;
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
//this.hostEndPoint = new IPEndPoint(address, port);
|
||||
//this.clientSocket = new Socket(this.hostEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
|
||||
}
|
||||
/// <summary>
|
||||
/// 连接服务端
|
||||
/// </summary>
|
||||
public string Send(String hostName, Int32 port, string message)
|
||||
{
|
||||
|
||||
string receiveMsg = "";
|
||||
IPAddress address = null;
|
||||
if (!String.IsNullOrEmpty(hostName))
|
||||
{
|
||||
IPAddress.TryParse(hostName, out address);
|
||||
}
|
||||
else
|
||||
{
|
||||
IPHostEntry host = Dns.GetHostEntry(hostName);
|
||||
IPAddress[] addressList = host.AddressList;
|
||||
foreach (IPAddress ad in addressList)
|
||||
{
|
||||
if (ad.AddressFamily == AddressFamily.InterNetwork)
|
||||
{
|
||||
address = ad;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
IPEndPoint hostPoint = new IPEndPoint(address, port);
|
||||
using (clientSocket = new Socket(hostPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
|
||||
{
|
||||
|
||||
clientSocket.Connect(hostPoint);
|
||||
clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 5000);
|
||||
byte[] sendMsg = Encoding.GetEncoding("GBK").GetBytes(message);
|
||||
clientSocket.Send(sendMsg);
|
||||
//设置超时
|
||||
//clientSocket.ReceiveTimeout = 5000;
|
||||
byte[] receiveByte = new byte[1024];
|
||||
int count = 0;
|
||||
try
|
||||
{
|
||||
count = clientSocket.Receive(receiveByte, receiveByte.Length, 0);//接受数据
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine(ex.Message + "接受信息超时!");
|
||||
}
|
||||
receiveMsg += Encoding.GetEncoding("GBK").GetString(receiveByte, 0, count);//转换为GBK格式的字符串
|
||||
receiveMsg = receiveMsg.Replace("\n\r", "");
|
||||
Console.WriteLine("接受信息:" + receiveMsg);
|
||||
}
|
||||
return receiveMsg;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TCP通信服务实例
|
||||
/// </summary>
|
||||
public static SyncSocketClient Instance
|
||||
{
|
||||
get
|
||||
{
|
||||
if (instance == null)
|
||||
{
|
||||
instance = new SyncSocketClient("", 3666);
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Configuration;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace HHWMS.Web
|
||||
{
|
||||
public class TcpService
|
||||
{
|
||||
|
||||
private SocketListener listener = null;
|
||||
|
||||
private int maxConnection = 100; //允许的最大连接数
|
||||
private int bufferSize = 1024 * 1024; //接收缓冲区的大小
|
||||
private int port = 3666; //监听的端口号
|
||||
private string ip = "127.0.0.1"; //监听的IP地址
|
||||
public TcpService(string listenerIp, int port)
|
||||
{
|
||||
this.port = port;
|
||||
this.ip = listenerIp;
|
||||
|
||||
StartService();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 处理客户端连接完成事件
|
||||
/// </summary>
|
||||
/// <param name="sender">客户端ip</param>
|
||||
/// <param name="e"></param>
|
||||
private void listener_ProcessAcceptComplete(object sender, SocketAsyncEventArgs e)
|
||||
{
|
||||
//触发处理客户端连接完成事件
|
||||
if (this.ProcessAcceptComplete != null)
|
||||
{
|
||||
this.ProcessAcceptComplete(sender, e);
|
||||
}
|
||||
}
|
||||
|
||||
private void listener_OnMsgReceived(string uid, byte[] info)
|
||||
{
|
||||
if (this.ReceiveMsgHandler != null)
|
||||
{
|
||||
this.ReceiveMsgHandler(uid, info);
|
||||
}
|
||||
//ICSharpCode.Core.LoggingService<TcpService>.Debug(String.Format("接收到{0}发送的消息:{1}", uid, info));
|
||||
}
|
||||
|
||||
private void listener_OnSended(string uid, string exception)
|
||||
{
|
||||
if (exception == "100")
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<TcpService>.Debug(String.Format("已发送消息到{0}", uid));
|
||||
}
|
||||
else
|
||||
{
|
||||
////ICSharpCode.Core.LoggingService.Error(String.Format("消息发送错误:{0}", exception));
|
||||
//ICSharpCode.Core.LoggingService<TcpService>.Warn("消息发送错误:客户端已经断开连接!");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 客户端断开连接的事件处理程序
|
||||
/// </summary>
|
||||
/// <param name="uid"></param>
|
||||
private void listener_OnClientClose(string uid)
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<TcpService>.Debug(String.Format("{0}:断开了连接...{1:yyyy-MM-dd HH:mm:ss}", uid, DateTime.Now));
|
||||
}
|
||||
|
||||
private void listener_StartListenThread()
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<TcpService>.Debug("开始侦听...");
|
||||
ThreadPool.QueueUserWorkItem(new WaitCallback(this.StartListenCallBack), true);
|
||||
}
|
||||
|
||||
private void StartListenCallBack(object listenFlag)
|
||||
{
|
||||
this.listener.ListenFlag = Convert.ToBoolean(listenFlag);
|
||||
this.listener.Listen();
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取侦听的服务器IP地址
|
||||
/// </summary>
|
||||
/// <param name="ip"></param>
|
||||
/// <returns></returns>
|
||||
private string GetIDByIP(string ip)
|
||||
{
|
||||
return ip;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 启动服务
|
||||
/// </summary>
|
||||
private void StartService()
|
||||
{
|
||||
try
|
||||
{
|
||||
////ICSharpCode.Core.LoggingService<TcpService>.Debug("最大连接数:" + this.maxConnection);
|
||||
//ICSharpCode.Core.LoggingService<TcpService>.Debug("侦听的端口号:" + this.port);
|
||||
this.listener = new SocketListener(this.maxConnection, this.bufferSize, this.GetIDByIP);
|
||||
this.listener.StartListenThread += new SocketListener.StartListenHandler(listener_StartListenThread);
|
||||
this.listener.ProcessAcceptComplete += new EventHandler<SocketAsyncEventArgs>(listener_ProcessAcceptComplete);
|
||||
this.listener.OnSended += new SocketListener.SendCompletedHandler(listener_OnSended);
|
||||
this.listener.OnMsgReceived += new SocketListener.ReceiveMsgHandler(listener_OnMsgReceived);
|
||||
this.listener.OnClientClose += new SocketListener.ClientClose(listener_OnClientClose);
|
||||
this.listener.Init();
|
||||
try
|
||||
{
|
||||
this.listener.Start(this.ip, this.port);
|
||||
}
|
||||
catch (System.Net.Sockets.SocketException se)
|
||||
{
|
||||
if (se.SocketErrorCode == System.Net.Sockets.SocketError.AddressAlreadyInUse)
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<TcpService>.Error(String.Format("端口号{0}已被占用!", this.port));
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<TcpService>.Error(ex.Message);
|
||||
//ICSharpCode.Core.LoggingService<TcpService>.Error(ex.StackTrace);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 重启服务
|
||||
/// </summary>
|
||||
public void ReStartService()
|
||||
{
|
||||
StopService();
|
||||
StartService();
|
||||
}
|
||||
/// <summary>
|
||||
/// 停止服务
|
||||
/// </summary>
|
||||
public void StopService()
|
||||
{
|
||||
try
|
||||
{
|
||||
this.listener.Stop();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//ICSharpCode.Core.LoggingService<TcpService>.Error("停止Socket侦听失败:" + ex.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
//this.listener = null;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 发送消息至所有连接至本服务器的客户端计算机
|
||||
/// </summary>
|
||||
/// <param name="msg">消息内容</param>
|
||||
public void NetSendMsg(string msg)
|
||||
{
|
||||
foreach (string uid in this.listener.OnlineUID)
|
||||
{
|
||||
this.listener.Send(uid, msg);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 发送消息至指定计算机
|
||||
/// </summary>
|
||||
/// <param name="uid">计算机IP地址</param>
|
||||
/// <param name="msg">消息内容</param>
|
||||
public void NetSendMsg(string uid, string msg)
|
||||
{
|
||||
this.listener.Send(uid, msg);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 接收到信息时触发的事件
|
||||
/// </summary>
|
||||
public event SocketListener.ReceiveMsgHandler ReceiveMsgHandler;
|
||||
/// <summary>
|
||||
/// 处理接收客户端连接完成事件
|
||||
/// </summary>
|
||||
public event EventHandler<SocketAsyncEventArgs> ProcessAcceptComplete;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user