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(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); } } /// /// 处理客户端连接完成事件 /// /// 客户端ip /// 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("消息发送错误:客户端已经断开连接!"); } } /// /// 客户端断开连接的事件处理程序 /// /// 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(); } /// /// 获取侦听的服务器IP地址 /// /// /// private string GetIDByIP(string ip) { return ip; } /// /// TCP通信服务实例 /// public static TcpService Instance { get { if (instance == null) { instance = new TcpService(); } return instance; } } /// /// 启动服务 /// public static void StartService() { if (instance == null) { instance = new TcpService(); } } /// /// 重启服务 /// public static void ReStartService() { StopService(); StartService(); } /// /// 停止服务 /// public static void StopService() { if (instance != null) { try { instance.listener.Stop(); } catch (Exception ex) { ICSharpCode.Core.LoggingService.Error("停止Socket侦听失败:" + ex.Message); } finally { instance = null; } } } /// /// 发送消息至所有连接至本服务器的客户端计算机 /// /// 消息内容 public void NetSendMsg(string msg) { foreach (string uid in this.listener.OnlineUID) { this.listener.Send(uid, msg); } } /// /// 发送消息至指定计算机 /// /// 计算机IP地址 /// 消息内容 public void NetSendMsg(string uid, string msg) { this.listener.Send(uid, msg); } /// /// 接收到信息时触发的事件 /// public event SocketListener.ReceiveMsgHandler ReceiveMsgHandler; /// /// 处理接收客户端连接完成事件 /// public event EventHandler ProcessAcceptComplete; } }