You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

212 lines
7.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Configuration;
using System.Net.Sockets;
namespace Mesnac.Communication
{
public class TcpService
{
private static TcpService instance = null;
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地址
private TcpService()
{
try
{
object oMaxConnection = ConfigurationManager.AppSettings["MaxConnection"];
if (oMaxConnection != null)
{
int.TryParse(oMaxConnection.ToString(), out this.maxConnection);
}
object oPort = ConfigurationManager.AppSettings["Port"];
if (oPort != null)
{
int.TryParse(oPort.ToString(), out this.port);
}
ICSharpCode.Core.LoggingService.Debug("最大连接数:" + this.maxConnection);
ICSharpCode.Core.LoggingService.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.port);
}
catch(System.Net.Sockets.SocketException se)
{
if (se.SocketErrorCode == System.Net.Sockets.SocketError.AddressAlreadyInUse)
{
ICSharpCode.Core.LoggingService.Error(String.Format("端口号{0}已被占用!", this.port));
}
}
}
catch (Exception ex)
{
ICSharpCode.Core.LoggingService.Error(ex.Message);
ICSharpCode.Core.LoggingService.Error(ex.StackTrace);
}
}
/// <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, string info)
{
if (this.ReceiveMsgHandler != null)
{
this.ReceiveMsgHandler(uid, info);
}
ICSharpCode.Core.LoggingService.Debug(String.Format("接收到{0}发送的消息:{1}", uid, info));
}
private void listener_OnSended(string uid, string exception)
{
if (exception == "100")
{
ICSharpCode.Core.LoggingService.Debug(String.Format("已发送消息到{0}", uid));
}
else
{
//ICSharpCode.Core.LoggingService.Error(String.Format("消息发送错误:{0}", exception));
ICSharpCode.Core.LoggingService.Warn("消息发送错误:客户端已经断开连接!");
}
}
/// <summary>
/// 客户端断开连接的事件处理程序
/// </summary>
/// <param name="uid"></param>
private void listener_OnClientClose(string uid)
{
ICSharpCode.Core.LoggingService.Debug(String.Format("{0}:断开了连接...{1:yyyy-MM-dd HH:mm:ss}", uid, DateTime.Now));
}
private void listener_StartListenThread()
{
ICSharpCode.Core.LoggingService.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>
/// TCP通信服务实例
/// </summary>
public static TcpService Instance
{
get
{
if (instance == null)
{
instance = new TcpService();
}
return instance;
}
}
/// <summary>
/// 启动服务
/// </summary>
public static void StartService()
{
if (instance == null)
{
instance = new TcpService();
}
}
/// <summary>
/// 重启服务
/// </summary>
public static void ReStartService()
{
StopService();
StartService();
}
/// <summary>
/// 停止服务
/// </summary>
public static void StopService()
{
if (instance != null)
{
try
{
instance.listener.Stop();
}
catch (Exception ex)
{
ICSharpCode.Core.LoggingService.Error("停止Socket侦听失败:" + ex.Message);
}
finally
{
instance = 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;
}
}