本系列僅介紹可用于生產(chǎn)環(huán)境的C#異步Socket框架,如果您在其他地方看到類(lèi)似的代碼,不要驚訝,那可能就是我在參考開(kāi)源代碼時(shí),直接“剽竊”過(guò)來(lái)的。
1、在腦海里思考一下整個(gè)socket的鏈接的處理流程,于是便有了下圖。

2、首先就開(kāi)始監(jiān)聽(tīng),代碼如下:

public override bool Start() { this._socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, PRotocolType.Tcp); //設(shè)置KeeyAlive,如果客戶(hù)端不主動(dòng)發(fā)消息時(shí),Tcp本身會(huì)發(fā)一個(gè)心跳包,來(lái)通知服務(wù)器,這是一個(gè)保持通訊的鏈接。 //避免等到下一次通訊時(shí),才知道鏈接已經(jīng)斷開(kāi)。 this._socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); this._socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true); try { this._socket.Bind(base.SocketConfig.Point); this._socket.Listen(base.SocketConfig.Backlog); this._socket_args = new SocketAsyncEventArgs(); this._socket_args.Completed += new EventHandler<SocketAsyncEventArgs>(AcceptSocketCompleted); //在鏈接過(guò)來(lái)的時(shí)候,如果IO沒(méi)有掛起,則AcceptAsync為False,表明同步完成。 if (!this._socket.AcceptAsync(this._socket_args)) { AcceptSocketCompleted(this._socket, this._socket_args); } return true; } catch (Exception ex) { return false; } }void AcceptSocketCompleted(object sender, SocketAsyncEventArgs e) { System.Net.Sockets.Socket socket = null; if (e.SocketError != SocketError.Success) { return; } else { socket = e.AcceptSocket; } e.AcceptSocket = null; bool willRaiseEvent = false; try { //繼續(xù)監(jiān)聽(tīng)該端口,在處理邏輯時(shí),不影響其他鏈接的數(shù)據(jù)傳送。 willRaiseEvent = this._socket.AcceptAsync(e); } catch (Exception ex) { willRaiseEvent = true; } if (socket != null) OnNewClientAccepted(socket, null); if (!willRaiseEvent) AcceptSocketCompleted(null, e); }View Code3、這個(gè)時(shí)候鏈接過(guò)來(lái)了,就要開(kāi)始入隊(duì)列了,如果沒(méi)有這方面的需求,這一步可以忽略,代碼如下:

public class SocketProxy { public System.Net.Sockets.Socket Client; public DateTime Timeout = DateTime.Now; }public class SocketConnectionQueue : IDisposable { private Queue<SocketProxy> _queue; private readonly object _syncObject = new object(); private bool _isStop = false; private Thread _thread; public Action<SocketProxy> Connected; public SocketConnectionQueue() { if (_queue == null) { _queue = new Queue<SocketProxy>(); } if (_thread == null) { _thread = new Thread(Thread_Work) { IsBackground = true, Priority = ThreadPriority.Highest }; _thread.Start(); } } public void Push(SocketProxy connect) { lock (_syncObject) { if (_queue != null) { _queue.Enqueue(connect); } } } public void Thread_Work() { while (!_isStop) { SocketProxy[] socketConnect = null; lock (_syncObject) { if (_queue.Count > 0) { socketConnect = new SocketProxy[_queue.Count]; _queue.CopyTo(socketConnect, 0); _queue.Clear(); } } if (socketConnect != null && socketConnect.Length > 0) { foreach (var client in socketConnect) { if (Connected != null) { Connected.Invoke(client); } } } Thread.Sleep(10); } } public void Dispose() { _isStop = true; if (_thread != null) { _thread.Join(); } } }View Code4、入完隊(duì)列,就要開(kāi)始從鏈接池子里面分配資源了,你也可以不做鏈接池,在每次請(qǐng)求過(guò)來(lái)的時(shí)候去實(shí)例化一個(gè)鏈接,然后將這個(gè)鏈接入池,我的做法是在程序初始化的時(shí)候就分配好一定的資源,代碼如下:

public class SocketConnectionPool : IDisposable { private ServerConfig _serverConfig; public IAppServer AppServer; private ConcurrentStack<SocketConnection> _connectPool; private long connect_id = 0; private byte[] _buffer; private readonly object _syncObject = new object(); private SocketConnectionQueue _queue; public Action<System.Net.Sockets.Socket, SocketConnection> Connected; public long GenerateId() { if (connect_id == long.MaxValue) { connect_id = 0; } connect_id++; return connect_id; } public SocketConnectionPool(IAppServer server) { this.AppServer = server; this._serverConfig = server.AppConfig; } public void Init() { var connects = new List<SocketConnection>(this._serverConfig.MaxConnectionNumber); _buffer = new byte[this._serverConfig.BufferSize]; SocketAsyncEventArgs arg; for (var i = 0; i < this._serverConfig.MaxConnectionNumber; i++) { arg = new SocketAsyncEventArgs(); arg.SetBuffer(_buffer, 0, _buffer.Length); connects.Add(new SocketConnection(arg, this)); } _connectPool = new ConcurrentStack<SocketConnection>(connects); if (_queue == null) { _queue = new SocketConnectionQueue(); } _queue.Connected = OnConnected; } public void Push(System.Net.Sockets.Socket socket) { SocketProxy proxy = new SocketProxy() { Client = socket }; _queue.Push(proxy); } public void OnConnected(SocketProxy proxy) { //如果發(fā)現(xiàn)隊(duì)列里面的鏈接,在Timeout時(shí)間內(nèi),都沒(méi)有分配到資源,則關(guān)掉鏈接并丟棄。 int timeout = (int)(DateTime.Now - proxy.Timeout).TotalSeconds; if (timeout >= this._serverConfig.Timeout) { proxy.Client.Close(); return; } else { //沒(méi)有分配到資源重新入列。 SocketConnection connect = this.GetConnectionFromPool(); if (connect == null) { _queue.Push(proxy); } else { if
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注