Beispiel #1
0
 /// <summary>
 /// 开始一个服务器
 /// </summary>
 /// <param name="backlog"></param>
 public void Start(int backlog = 10)
 {
     socket.Bind(new IPEndPoint(IPAddress.Parse(m_IP), m_Port));
     socket.Listen(backlog);
     socket.BeginAccept(AcceptCallBack, null);
     ZLogger.Debug("     服务器初始化成功!   ");
 }
Beispiel #2
0
 private void ReceiveHead(IAsyncResult ar)
 {
     try
     {
         int len = conn.EndReceive(ar);
         if (len > 0)
         {
             currHeadIndex += len;
             if (currHeadIndex < headLength)
             {
                 conn.BeginReceive(headCache, currHeadIndex, headLength - currHeadIndex, SocketFlags.None
                                   , new AsyncCallback(ReceiveHead), null);
             }
             else
             {
                 bodyLength = ZNetConfig.isLittleEndian ? ZTool.ConvertToIntLittleEndian(headCache)
                     : ZTool.ConvertToIntBigEndian(headCache);
                 initBodyCache();
                 conn.BeginReceive(bodyCache, 0, bodyLength, SocketFlags.None
                                   , new AsyncCallback(ReceiveBody), null);
             }
         }
         else
         {
             ZLogger.Debug(" ZReceive 002:用户" + connectId + " 连接已断开", LogType.Warning);
             Close();
         }
     }
     catch (System.Exception ex)
     {
         ZLogger.Debug(" ZReceive 003:用户" + connectId + " 连接已断开", LogType.Warning);
         Close();
     }
 }
Beispiel #3
0
 public void StartReceive( )
 {
     try
     {
         conn.BeginReceive(headCache, 0, headLength, SocketFlags.None
                           , new AsyncCallback(ReceiveHead), null);
     }
     catch (System.Exception)
     {
         ZLogger.Debug(" ZReceive 001:用户" + connectId + " 连接已断开", LogType.Warning);
         Close();
     }
 }
Beispiel #4
0
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="data"></param>
        public void Send(Socket conn, System.Object obj, string connectId = null)
        {
            string datastr = null;

            try
            {
                datastr = JsonConvert.SerializeObject(obj);
            }
            catch (System.Exception ex)
            {
                ZLogger.Debug("ZSend 001:传输数据无法被序列化为Json:" + ex.ToString(), LogType.Error);
                ZLogger.Debug("停止发送本条消息!");
                return;
            }

            byte[] data = ZNetConfig.encoding.GetBytes(datastr);

            if (datastr == "\"\"")
            {
                ZLogger.Debug("ZSend 002:无法传递空消息:", LogType.Error);
                ZLogger.Debug("停止发送本条消息!");
                return;
            }
            else if (data.Length > ZNetConfig.MaxMessageSize)
            {
                ZLogger.Debug("ZSend 003: 单次发送消息过长", LogType.Error);
                ZLogger.Debug("停止发送本条消息!");
                return;
            }
            data = ZTool.Pack(data, ZNetConfig.isLittleEndian);

            try
            {
                conn.BeginSend(data, 0, data.Length, SocketFlags.None,
                               new AsyncCallback((IAsyncResult ar) =>
                {
                    conn.EndSend(ar);
                    OnEndSend?.Invoke(connectId);
                }), null);
            }
            catch (System.Exception ex)
            {
                OnDisConnected?.Invoke(connectId); //关闭连接
                conn?.Dispose();
                conn?.Close();
                conn = null;
                ZLogger.Debug("ZSend 003: 用户:" + connectId + " 连接已经断开", LogType.Warning);
            }
        }
Beispiel #5
0
        public void Send(string connectedId, object obj)
        {
            Socket clientSocket = null;

            if (!clients.TryGetValue(connectedId, out clientSocket))
            {
                ZLogger.Debug("ZServer 001 : 发送对象无效,停止发送!", LogType.Error);
                return;
            }

            zSend.SetOnDisConnected((str) =>
            {
                clients.TryRemove(connectedId, out Socket _);
                OnDisConnected?.Invoke(str);
            });
            zSend.Send(clientSocket, obj, connectedId);
        }
Beispiel #6
0
        private void ReceiveBody(IAsyncResult ar)
        {
            try
            {
                int len = conn.EndReceive(ar);
                if (len > 0)
                {
                    currBodyIndex += len;
                    if (currBodyIndex < headLength)
                    {
                        conn.BeginReceive(bodyCache, currBodyIndex, bodyLength - currBodyIndex, SocketFlags.None
                                          , new AsyncCallback(ReceiveBody), null);
                    }
                    else
                    {
                        string        str = ZNetConfig.encoding.GetString(bodyCache);
                        System.Object obj = JsonConvert.DeserializeObject(str);

                        OnEndReceive?.Invoke(connectId, obj);

                        clearCache();
                        initHeadCache();
                        conn.BeginReceive(headCache, 0, headLength, SocketFlags.None
                                          , new AsyncCallback(ReceiveHead), null);
                    }
                }
                else
                {
                    ZLogger.Debug(" ZReceive 003:用户" + connectId + " 连接已断开", LogType.Warning);
                    Close();
                }
            }
            catch (System.Exception ex)
            {
                ZLogger.Debug(" ZReceive 004:用户" + connectId + " 连接已断开", LogType.Warning);
                Close();
            }
        }
Beispiel #7
0
        public void Start()
        {
            try
            {
                socket.BeginConnect(IPAddress.Parse(m_IP), m_Port, (ar) =>
                {
                    try
                    {
                        socket.EndConnect(ar);
                    }
                    catch (System.ObjectDisposedException)
                    {
                        ZLogger.Debug(" ZClient 001: 连接已断开", LogType.Warning);
                        return;
                    }
                    catch (System.Net.Sockets.SocketException) {
                        ZLogger.Debug(" ZClient 002: 服务器未启动", LogType.Warning);
                        return;
                    }
                    OnConnected?.Invoke();
                    ZReceive zr = new ZReceive(
                        connSocket: socket
                        , onDisConnected: (_) => OnDisConnected?.Invoke()
                        , onEndReceive: (_, obj) => OnEndReceive?.Invoke(obj)
                        );
                    zr.StartReceive();
                }, null);
            }
            catch (System.Exception)
            {
                ZLogger.Debug(" ZClient 003: 连接已断开", LogType.Warning);
                return;
            }

            ZLogger.Debug("     客户端初始化成功!   ");
        }