Server

作者: 高呼吾名 | 来源:发表于2020-05-08 02:03 被阅读0次
    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Collections.Generic;
    using System.Diagnostics;
    public class Server {
        private Socket serverSocket;
        //private Semaphore acceptSemaphore;
        private ClientPeerPool clientPeerPool;
    
    
        private IApplication application;
        public void SetApplication(IApplication app) {
            application = app;
        }
    
    
        public void Start(int port, int maxCount) {
    
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    
            //acceptSemaphore = new Semaphore(maxCount, maxCount);
    
            clientPeerPool = new ClientPeerPool(maxCount);
            ClientPeer tmpClientPeer = null;
            for (int i = 0; i < maxCount; i++) {
                tmpClientPeer = new ClientPeer();
                tmpClientPeer.ReceiveArgs.Completed += receive_Complete;
                tmpClientPeer.receiveCompleted = receiveCompleted;
                tmpClientPeer.sendDisconnect = Disconnect;
                clientPeerPool.Enqueue(tmpClientPeer);
            }
    
    
    
            serverSocket.Bind(new IPEndPoint(IPAddress.Any, port));
    
            serverSocket.Listen(maxCount);
    
            Console.WriteLine(TimerManager.GetNowTime() + "服务器启动...监听的端口为" + port);
    
            startAccept(null);
        }
    
        public void Abort() {
            if (serverSocket == null) {
                return;
            }
            ClientCache.CloseAllClient();
            closed = true;
            serverSocket.Dispose();
            serverSocket.Close();
            Console.WriteLine("关闭服务器");
        }
    
        #region 连接
        //开始等待客户端连接
        private void startAccept(SocketAsyncEventArgs e) {
            if (e == null) {
                e = new SocketAsyncEventArgs();
                e.Completed += accept_Completed;
            }
            //判断异步事件是否执行完毕 true 表示正在执行,执行完触发completed事件 。false表示执行完成 未执行completed事件
            bool result = serverSocket.AcceptAsync(e);
    
            if (result == false) {
                processAccept(e);
            }
    
        }
    
    
        //接收连接请求异步事件成功时触发
        private void accept_Completed(object sender,SocketAsyncEventArgs e) {
            processAccept(e);
        }
    
        //处理连接请求
        private void processAccept(SocketAsyncEventArgs e) {
            //限制线程访问
            //acceptSemaphore.WaitOne();
    
            ClientPeer client = clientPeerPool.Dequeue();
            client.ClientSocket = e.AcceptSocket;
    
            Console.WriteLine(TimerManager.GetNowTime()+"客户端连接成功 :" + client.ClientSocket.RemoteEndPoint.ToString());
    
            ClientCache.AddClientCache(client);
    
            //startReceive(client);
            client.StartReceiveTask();
    
            e.AcceptSocket = null;
            startAccept(e);
        }
    
        #endregion
    
        byte[] buffer = new byte[102400];
        #region 接收数据
        public bool closed = false;
        //开始接收数据
        private void startReceive(ClientPeer client) {
            bool result = client.ClientSocket.ReceiveAsync(client.ReceiveArgs);
            if (result == false) {
                processReceive(client.ReceiveArgs);
            }
            client.ClientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallBack, client);
        }
    
        private void ReceiveCallBack(IAsyncResult ar) {
            string str = "";
        }
    
    
    
        //处理接收到的数据请求
        private void processReceive(SocketAsyncEventArgs e) {
            ClientPeer client = e.UserToken as ClientPeer;
            if (client.ReceiveArgs.SocketError == SocketError.Success && client.ReceiveArgs.BytesTransferred > 0) {
                byte[] packet = new byte[client.ReceiveArgs.BytesTransferred];
                Buffer.BlockCopy(client.ReceiveArgs.Buffer, 0, packet, 0, client.ReceiveArgs.BytesTransferred);
                //if(!closed)
                client.StartReceive(packet);
                startReceive(client);
            } else if(client.ReceiveArgs.BytesTransferred == 0) {
                if (client.ReceiveArgs.SocketError == SocketError.Success) {
                    Disconnect(client, "客户端主动断开");
                }
            }
        }
    
    
    
    
        #endregion
    
    
        //client对象 接收消息完成时 触发的事件
        private void receive_Complete(object sender, SocketAsyncEventArgs e) {
            processReceive(e);
        }
    
    
        //client对象 将一条数据解析完成时的处理
        private void receiveCompleted(ClientPeer client, SocketMsg msg) {
            application.OnReceive(client, msg);
        }
    
    
        #region 断开连接
    
    
    
        //断开连接
        public void Disconnect(ClientPeer client,string reason) {
            SingleExecute.Instance.Execute(() => {
                if (client == null) {
                    Console.WriteLine(TimerManager.GetNowTime() + client.ToString() + "当前指定的客户端连接对象为空,无法断开连接");
                    return;
                }
                Console.WriteLine(TimerManager.GetNowTime() + client.ClientSocket.RemoteEndPoint.ToString() + "客户端断开连接 原因" + reason);
                if (reason == "客户端主动断开连接") {
                    application.OnDisconnect(client, 0);
                } else {
                    application.OnDisconnect(client, -1);
                }
                //移除client缓存
                ClientCache.RemoveClientCache(client);
                client.Disconnect();
                //回收对象方便下次使用
                clientPeerPool.Enqueue(client);
                //acceptSemaphore.Release();
            });
    
        }
        #endregion
    
    }
    

    相关文章

      网友评论

          本文标题:Server

          本文链接:https://www.haomeiwen.com/subject/btatnhtx.html