监听器宿主是windows服务,
windows服务代码:
public partial class KFService : ServiceBase
{
Server Srv = new Server();
public KFService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
string Msg;
if (!Srv.Start(out Msg))
{
throw new Exception(Msg);
//this.Stop();
//this.EventLog.WriteEntry(Msg);
}
}
protected override void OnStop()
{
Srv.Stop();
}
}
Server.cs
public class Server
{
/// <summary>
/// 主服务线程
/// </summary>
private Thread _VSTServiceProccess;
/// <summary>
/// TCP服务Socket
/// </summary>
private TcpListener _PDAService;
/// <summary>
/// 服务超时间隔
/// </summary>
private int _ServiceTimeOut;
/// <summary>
/// 服务器的IP
/// </summary>
private IPAddress _ServerIP;
/// <summary>
/// 服务器的服务端口
/// </summary>
private int _ServerPoint;
private byte[] _TransmitKey = null;
private string _TransmitReaderSn = null;
//Distinguisher.DistinguisherEquement _DrEquement = null;
private void WriteLog(string Msg)
{
try
{
WritLogFile.Log.WriteFile(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff-->") + Msg);
}
catch
{ }
}
public Server()
{
_ServiceTimeOut = 60;
_ServerIP = IPAddress.Any;
_ServerPoint = 33555;
if (!int.TryParse(ConfigurationManager.AppSettings["ServerPort"], out _ServerPoint))
{
_ServerPoint = 33555;
WriteLog("ServerStart:获取主通信端口失败");
}
}
/// <summary>
/// 服务进程启动
/// </summary>
public bool Start(out string ErrMsg)
{
ErrMsg = null;
try
{
if (_VSTServiceProccess != null)
{
_VSTServiceProccess.Abort();
_VSTServiceProccess = null;
}
Thread.Sleep(50);
//本地打开TCP监听
_PDAService = new TcpListener(_ServerIP, _ServerPoint);
_PDAService.Start();
/*循环接收_PDAService监听数据
* 创建后台线程m_SendDatas用来发送数据
* 最后创建一个新线程ServiceProccess,用来处理已收到的TCP请求,调用m_SendDatas异步发送数据
*/
_VSTServiceProccess = new Thread(this.PDAServiceProccess);
_VSTServiceProccess.Start();
WriteLog("服务启动成功,端口号:" + _ServerPoint.ToString());
return true;
}
catch (Exception ex)
{
ErrMsg = "服务器启动失败,异常信息 :" + ex.Message;
WriteLog(ErrMsg);
return false;
}
}
/