Example #1
0
 public ClientWorkingPolicy(ResponsePolicy policy, ClientManager client, ISocketMessage msg, bool noDelay)
 {
     this.Policy  = policy;
     this.Client  = client;
     this.Message = msg;
     this.NoDelay = noDelay;
 }
 public ClientWorkingPolicy(ResponsePolicy policy, ClientManager client, ISocketMessage msg, bool noDelay)
 {
     this.Policy = policy;
     this.Client = client;
     this.Message = msg;
     this.NoDelay = noDelay;
 }
Example #3
0
 public QueuedOutMessage(ClientManager clmngr, ISocketMessage msg, bool shutdown)
 {
     this.Client  = clmngr;
     this.Command = msg;
     this.Length  = 0;
     this.ShutdownClientAfterSend = shutdown;
 }
Example #4
0
        /// <summary>
        /// 向客户端下发消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        public virtual CommonResult NotifyClient(object sender, ClientNotifEventArgs e)
        {
            int[]          sessionIDs = e.Recvs;
            ISocketMessage msg        = e.Command;
            ClientManager  clmngr     = null;
            CommonResult   result     = CommonResult.OtherError;

            try
            {
                if (sessionIDs == null || sessionIDs.Length < 1 || msg == null)
                {
                    return(CommonResult.NoData);
                }
                foreach (int sessionID in sessionIDs)
                {
                    if (!_Clients.ContainsKey(sessionID))
                    {
                        continue;
                    }
                    clmngr = this._Clients[sessionID] as ClientManager;
                    AppendToOutMessageQueue(new QueuedOutMessage(clmngr, msg));
                }

                result = CommonResult.Success;
            }
            catch (Exception ex)
            {
                DebugMessage(string.Format("NotifiClient Error:{0};Source:{1}", ex.Message, ex.Source));
                result = CommonResult.SystemError;
            }
            finally { }

            return(result);
        }
 public QueuedOutMessage(ClientManager clmngr, ISocketMessage msg)
 {
     this.Client = clmngr;
     this.Command = msg;
     this.Length = 0;
     this.ShutdownClientAfterSend = false;
 }
Example #6
0
        public void Handle(Type type, ISocketMessage message, StateObject context)
        {
            var serviceType = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).Where(s => s.GetInterface(typeof(IHandleMessage).Name) != null).FirstOrDefault(a => a.GetInterfaces().Any(s => s.IsGenericType && s.GenericTypeArguments[0] == type));
            var service     = (IHandleMessage)Activator.CreateInstance(serviceType.Assembly.FullName, serviceType.FullName).Unwrap();

            serviceType.GetMethods().FirstOrDefault(x => x.GetParameters().Any(a => a.ParameterType == type)).Invoke(service, new object[] { message, context });
        }
Example #7
0
        public void Handle(Type type, ISocketMessage message, StateObject context)
        {
            var serviceType = typeof(IHandleMessage <>).MakeGenericType(type);

            var service = Container.Resolve(serviceType);

            serviceType.GetMethods().FirstOrDefault(x => x.GetParameters().Any(a => a.ParameterType == type)).Invoke(service, new object[] { message, context });
        }
Example #8
0
        private void Send(ISocketMessage socketMessage)
        {
            var byteData = _serializer.Serialize(socketMessage);

            BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), this);

            sendDone.WaitOne();
        }
Example #9
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="tConfig">Socket基础配置</param>
 /// <param name="protocolType">Socket 类型,默认为TCP</param>
 /// <param name="autoconnec">是否重连</param>
 /// <param name="autoConnecSecond">重连间隔</param>
 /// <param name="bufferSize">自定义的缓冲区大小,</param>
 /// <param name="ISocketMessage">自定义回调,</param>
 public TSock(TConfig tConfig, ISocketMessage socketMessage, ProtocolType protocolType = ProtocolType.Tcp, bool autoconnec = true, int autoConnecSecond = 1000, int bufferSize = 1024)
 {
     this.bufferSize    = bufferSize;
     this.socketMessage = socketMessage;
     InitLize(tConfig);
     this.autoConnecSecond = autoConnecSecond;
     this.protocolType     = protocolType;
     this.autoconnec       = autoconnec;
 }
Example #10
0
        public virtual CommonResult BroadCastToClient(object sender, ClientNotifEventArgs e)
        {
            CommonResult   result    = CommonResult.InvalidParams;
            ISocketMessage msg       = e.Command;
            int            senderUID = e.Sender;

            int[] keys = null;

            try
            {
                if (this._Clients.Keys.Count > 0)
                {
                    //  如果指定了广播受众
                    if (e.Recvs != null && e.Recvs.Length > 0)
                    {
                        keys = e.Recvs;
                    }
                    else
                    {
                        //  否则群发
                        lock (this._Clients.SyncRoot)
                        {
                            if (this._Clients.Keys.Count < 1)
                            {
                                return(CommonResult.Success);
                            }
                            keys = new int[this._Clients.Keys.Count];
                            this._Clients.Keys.CopyTo(keys, 0);
                        }
                    }

                    if (keys != null && keys.Length > 0)
                    {
                        ClientManager clmngr = null;
                        foreach (int uid in keys)
                        {
                            //  如果发送人是普通用户,则检查其是否在某个用户的黑名单里
                            if (this._Clients.ContainsKey(uid))
                            {
                                clmngr = this._Clients[uid] as ClientManager;
                                AppendToOutMessageQueue(new QueuedOutMessage(clmngr, msg));
                            }
                        }
                    }
                }
                result = CommonResult.Success;
            }
            catch (Exception ex)
            {
                DebugMessage(string.Format("BroadCastToClient Error:{0};Source:{1}", ex.Message, ex.Source));
                result = CommonResult.SystemError;
            }
            finally { }

            return(result);
        }
Example #11
0
        public InternalServer(IPAddress ipAddress, int port, ILogger logger)
        {
            _logger = logger;

            TcpListener    = new TcpListener(ipAddress, port);
            _socketMessage = new JsonSocketMessage();
            Clients        = new Dictionary <Socket, Guid>();

            ServerId = Guid.NewGuid();
        }
        public ISocketMessage CreateCustomer(ISocketMessage socketMessage)
        {
            var createCustomerCommand = (CreateCustomerCommand)socketMessage;

            return(new CustomerCreatedReply
            {
                CorrelationId = createCustomerCommand.CorrelationId,
                CustomerId = Guid.NewGuid().ToString()
            });
        }
Example #13
0
        public void Send(ISocketMessage messageBase)
        {
            try
            {
            }

            catch (Exception e)
            {
                _logger.Warn(e.Message);
            }
        }
        public ISocketMessage PlaceOrder(ISocketMessage socketMessage)
        {
            var placeOrderCommand = (PlaceOrderCommand)socketMessage;

            return(new OrderPlacedReply
            {
                CorrelationId = placeOrderCommand.CorrelationId,
                CustomerId = placeOrderCommand.CustomerId,
                OrderId = "OIX-111-120618",
                PlacedAt = DateTime.Now
            });
        }
        public ISocketMessage GetOrders(ISocketMessage socketMessage)
        {
            var getOrdersCommand = (GetOrdersCommand)socketMessage;

            return(new OrdersReply
            {
                CorrelationId = getOrdersCommand.CorrelationId,
                CustomerName = "John Doe",
                OrderId = getOrdersCommand.OrderId,
                PlacedAt = DateTime.Now.AddMonths(-2)
            });
        }
Example #16
0
        public virtual void SendToClient(int sessionID, ISocketMessage msg)
        {
            if (sessionID <= 0 || msg == null)
            {
                return;
            }

            if (this._Clients.ContainsKey(sessionID))
            {
                ClientManager clmngr = this._Clients[sessionID] as ClientManager;
                SendToClient(clmngr, msg);
            }
        }
Example #17
0
    /// <summary>
    /// 创建TCP对象接口
    /// </summary>
    /// <param name="config"></param>
    /// <param name="protocolType"></param>
    /// <param name="autoconnec"></param>
    /// <param name="autoConnecSecond"></param>
    /// <param name="bufferSize"></param>
    /// <returns></returns>
    public TSock CreateTcpSocket(TConfig config, ISocketMessage socketMessage, bool autoconnec = true, int autoConnecSecond = 1000, int bufferSize = 1024)
    {
        TSock sock = new TSock(config, socketMessage, ProtocolType.Tcp, autoconnec, autoConnecSecond, bufferSize);
        var   temp = tcpSockList.Find(m => m.tConfig.name.Equals(config.name));

        if (temp != null)
        {
            temp.Dispose();
            tcpSockList.Remove(temp);
        }
        tcpSockList.Add(sock);
        return(sock);
    }
Example #18
0
        public Task Write(ISessionData session, ISocketClient client, ISocketMessage message)
        {
            try
            {
                WhenWriting(session, client, message);
            }
            catch (Exception oops)
            {
                Debug.WriteLine(ToString() + "|" + oops.Message);
                return(Task.FromException(oops));
            }

            return(Task.CompletedTask);
        }
Example #19
0
        public override void Add(ISocketMessage message)
        {
            if (_messages.TryAdd(message.Id, message))
            {
                _orderedMessages.Enqueue(message.Id);

                ulong          msgId;
                ISocketMessage msg;
                while (_orderedMessages.Count > _size && _orderedMessages.TryDequeue(out msgId))
                {
                    _messages.TryRemove(msgId, out msg);
                }
            }
        }
Example #20
0
        public SocketMessageEventArgs(ISocketMessage message, ISocketWriter writer)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer));
            }

            this.Message = message;
            this.SocketWriter = writer;
        }
Example #21
0
        public T Call <T>(ISocketMessage socketMessage) where T : ISocketMessage
        {
            T response;

            using (var socketClient = new SocketClient(_remoteEndpoint))
            {
                socketClient.StartClient();

                response = socketClient.Call <T>(socketMessage);

                socketClient.Shutdown(SocketShutdown.Both);
                socketClient.Close();
            }
            return(response);
        }
Example #22
0
        public void Send(Socket socket, ISocketMessage messageBase)
        {
            try
            {
                if (socket.Connected)
                {
                    byte[] serialized = messageBase.Serialize();

                    Socket.BeginSendTo(serialized, 0, serialized.Length, 0, socket.RemoteEndPoint, SendCallback, socket);
                }
            }
            catch (SocketException e)
            {
                _logger.Warn(e.Message);
            }
        }
Example #23
0
        public byte[] Serialize(ISocketMessage socketMessage)
        {
            var jsonContent = JsonConvert.SerializeObject(socketMessage);
            var jsonBytes   = _encoding.GetBytes(jsonContent);

            var bytes            = new byte[jsonBytes.Length + SocketMessageHeaders.MessageSizeEndIndex];
            var messageSizeBytes = BitConverter.GetBytes(jsonBytes.Length);

            //Set the message size using the first 4 bytes of the array.
            Buffer.BlockCopy(messageSizeBytes, 0, bytes, 0, messageSizeBytes.Length);

            //Fill the rest of the array with the socketMessage
            Buffer.BlockCopy(jsonBytes, 0, bytes, messageSizeBytes.Length, jsonBytes.Length);

            return(bytes);
        }
        private bool ProcessMessage(ISessionData session, ISocketClient client, ISocketMessage message)
        {
            var user = _clientStates.Values.Where(c => c.ConnectionId == client.ConnectionId).SingleOrDefault();

            byte[] bytes = message.GetRawBytes();

            string result = (bytes[0]) switch
            {
                (byte)'/' => ProcessSlashCommand(user, session, client, ref bytes),
                (byte)'?' => GetHelpText(),
                _ => "Bad command or file name." // :)
            };

            client.Send(Encoding.ASCII.GetBytes(result + "\n"));

            return(true);
        }
        public void Send(ISocketMessage socketMessageBase)
        {
            try
            {
                Socket client = TcpClient.Client;

                if (!client.Connected)
                {
                    return;
                }

                byte[] serialized = socketMessageBase.Serialize();

                client.BeginSend(serialized, 0, serialized.Length, 0, SendMessageCallback, client);
            }

            catch (Exception e)
            {
                _logger.Warn(e.Message);
            }
        }
Example #26
0
        public void SendAsc(QueuedOutMessage msg)
        {
            try
            {
                if (msg == null || msg.Client == null || !msg.Client.Socket.Connected || msg.Command == null)
                {
                    return;
                }

                ClientManager  clmngr  = msg.Client;
                ISocketMessage message = msg.Command;

                byte[] buf = message.GetBytes();
                msg.Length = (uint)buf.Length;
                msg.ShutdownClientAfterSend = true;
                clmngr.Socket.BeginSend(buf, 0, buf.Length, SocketFlags.None, new AsyncCallback(SendAscyCallback), msg);
            }
            catch
            {
            }
            finally { }
        }
Example #27
0
        public virtual void SendToClient(ClientManager clmngr, ISocketMessage msg)
        {
            try
            {
                if (clmngr == null || msg == null || msg.Length == 0)
                {
                    return;
                }

                byte[] buf = msg.GetBytes();
                if (buf == null || buf.Length < 1)
                {
                    return;
                }
                int i = clmngr.Socket.Send(buf, buf.Length, SocketFlags.None);
            }
            catch (Exception ex)
            {
                string strError = ex.Message;
                DebugMessage(string.Format("SendToClient Error:{0};Source:{1}", ex.Message, ex.Source));
            }
            finally { }
        }
        private bool ProcessPendingAuth(ISessionData session, ISocketClient client, ISocketMessage message)
        {
            var user = _clientStates.Values.Where(c => c.ConnectionId == client.ConnectionId).SingleOrDefault();

            //TODO: Error handling in chat server component

            var msg = message.GetRawBytes();

            if (msg.Length == 0 || msg.Length > 16)
            {
                client.Send(_("Invalid alias" + user.LinePrompt));
                return(false);
            }

            user.Alias = Encoding.ASCII.GetString(msg);
            user.Commands.Add(new JoinCommand()); //TODO: Populate commands based on access? Dunno
            user.Commands.Add(new ListRoomsCommand());

            client.Send(_($"Welcome {user.Alias}\n>"));

            user.Flags = ChatStates.Connected | ChatStates.Authenticated;

            return(true);
        }
Example #29
0
        /// <summary>
        /// 处理用户请求
        /// </summary>
        /// <param name="clmngr"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override bool HandleRequest(ClientManager clmngr, ISocketMessage message)
        {
            bool goRecieving = false;
            HttpContext context = null;
            try
            {
                _RequestTimes++;
                HttpRequest request = HttpRequest.ParseFromRawMessage(this, message.ToString());

                if (!request.IsRequestError)
                {
                    //检查主机头是否符合设置
                    if (!CheckRequestHost(request))
                    {
                        //shutdown client
                        ShutdownClient(clmngr);
                        return goRecieving;
                    }
                    //获取该request的handlers
                    CometCommandHandlerPipeline handlePipeline = GetRegistedCommandHandlers(request);

                    if (handlePipeline == null)
                    {
                        //shutdown client
                        ShutdownClient(clmngr);
                        return goRecieving;
                    }

                    context = new HttpContext(this, clmngr, request);

                    CometCommand cometCmd = handlePipeline.Command;
                    request.Command = cometCmd;

                    if (!clmngr.IsAuthedUser)
                    {
                        RegistUser(clmngr, request);
                    }
                    //如果要求长连接
                    if (cometCmd.RequireKeepAlive)
                    {
                        //登记本次请求事务
                        if (RegistKeepAliveRequestContext(clmngr, request) == null)
                        {
                            //shutdown client
                            ShutdownClient(clmngr);
                            return goRecieving;
                        }
                    }
                    //执行处理管道
                    if (handlePipeline.Count > 0)
                    {
                        foreach (Handler.IHttpHandler handler in handlePipeline.Handlers)
                        {
                            if (handler != null)
                            {
                                handler.HandleRequest(clmngr, context);
                            }
                        }
                    }
                }
                else
                {
                    HandleErrorRequest(clmngr, request);
                }
            }
            catch (Exception ex)
            {
                if (ex is BussinessException)
                {
                    ExceptionResult result = new ExceptionResult()
                    {
                        ErrorCode = "B10001",
                        ErrorMessage = ex.Message
                    };
                    context.Response.Write(Common.Utility.Json.JsonHelper.ObjToJson(result));
                }
                else
                {
                    ShutdownClient(clmngr);
                    Console.WriteLine(string.Format("Error occured when HandleRequest:{0} ", ex.Message));
                }
            }
            finally { }
            return goRecieving;
        }
        protected override void WhenReceiving(ISessionData session, ISocketClient client, ISocketMessage message)
        {
            /*  <-- INCOMING -->
             *  255 253 1    IAC DO ECHO
             *  255 253 31   IAC DO NAWS
             *  255 251 1    IAC WILL ECHO
             *  255 251 3    IAC WILL SUPPRESS-GO-AHEAD
             * */

            /*  <-- REPLY WITH -->
             *  255 252 1    IAC WONT ECHO
             *  255 252 31   IAC WONT NAWS
             *  255 254 1    IAC DONT ECHO
             *  255 254 3    IAC DONT SUPPRESS-GO-AHEAD
             * */

            // https://www.iana.org/assignments/telnet-options/telnet-options.xhtml


            var options = new List <TelnetPacketOption>();

            TelnetPacketOption option = null;

            byte b;
            byte lastByte = 0x00;

            var pos   = 0;
            var bytes = message.GetRawBytes(); // so is this bytes 'by ref'?

            if (message.FirstByte != B.Iac)    // wrong B.Iac value, hell... could be wrong acronym even.
            {
                goto DoneWithOptions;          // ignore the packet if it doesn't have any options? whatever
            }
            do
            {
                b = bytes[pos++]; // byte for the current position

                if (b == B.Iac)   // if it's an identifier for IAC then make a new option
                {
                    Debug.Write("IAC ");
                    if (lastByte == b) // if two IAC bytes (255, 0xFF) then the next byte starts content (if I recall, will look it up)
                    {
                        break;
                    }

                    option = new TelnetPacketOption();
                    options.Add(option);
                }

                option.Declaration = (bytes[pos++]) switch
                {
                    B.Will => TelnetDeclarations.Will,
                    B.Wont => TelnetDeclarations.Wont,
                    B.Do => TelnetDeclarations.Do,
                    B.Dont => TelnetDeclarations.Dont,

                    _ => TelnetDeclarations.None,
                };

                Debug.Write(Enum.GetName(typeof(TelnetDeclarations), option.Declaration) + " ");

                option.Value = (bytes[pos++]) switch
                {
                    (byte)TelnetOptions.Echo => TelnetOptions.Echo,
                    (byte)TelnetOptions.SupressGoAhead => TelnetOptions.SupressGoAhead,
                    (byte)TelnetOptions.FlowControl => TelnetOptions.FlowControl,

                    // moar

                    _ => TelnetOptions.Null,
                };

                Debug.WriteLine(Enum.GetName(typeof(TelnetOptions), option.Value));

                lastByte = b;
            }while (true);
 public ClientNotifEventArgs(int sender, int[] uids, ISocketMessage cmd)
 {
     this.Sender  = sender;
     this.Recvs   = uids;
     this.Command = cmd;
 }
Example #32
0
 public T Call <T>(ISocketMessage socketMessage) where T : ISocketMessage
 {
     Send(socketMessage);
     return(Receive <T>());
 }
Example #33
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="clmngr"></param>
 /// <param name="request"></param>
 /// <returns>true = 继续接收数据</returns>
 public virtual bool HandleRequest(ClientManager clmngr, ISocketMessage request)
 {
     return true;
 }
Example #34
0
        public virtual void SendToClient(int sessionID, ISocketMessage msg)
        {
            if (sessionID <= 0 || msg == null)
                return;

            if (this._Clients.ContainsKey(sessionID))
            {
                ClientManager clmngr = this._Clients[sessionID] as ClientManager;
                SendToClient(clmngr, msg);
            }
        }
        protected override void WhenReceiving(ISessionData session, ISocketClient client, ISocketMessage message)
        {
            var user = _clientStates.Values.Where(c => c.ConnectionId == client.ConnectionId).SingleOrDefault();

            if (user == null)
            {
                Debug.WriteLine($"{client.ConnectionId}: Invalid Connection");
                return;
            }

            var success = (user.Flags) switch // discarding to use cooler syntax
            {
                ChatStates.Connected
                | ChatStates.Authenticated => ProcessMessage(session, client, message),

                ChatStates.Connected
                | ChatStates.Authenticating => ProcessPendingAuth(session, client, message),

                _ => false
            };

            Debug.WriteLine($"{user.ConnectionId} {success}");
        }
Example #36
0
        public virtual void SendToClient(ClientManager clmngr, ISocketMessage msg)
        {
            try
            {
                if (clmngr == null || msg == null || msg.Length == 0)
                    return;

                byte[] buf = msg.GetBytes();
                if (buf == null || buf.Length < 1)
                    return;
                int i = clmngr.Socket.Send(buf, buf.Length, SocketFlags.None);
            }
            catch (Exception ex)
            {
                string strError = ex.Message;
                DebugMessage(string.Format("SendToClient Error:{0};Source:{1}", ex.Message, ex.Source));
            }
            finally { }
        }
Example #37
0
        protected virtual void OnMessageReceived(SocketHandler handler, ISocketMessage message)
        {
            trace.TraceEvent(TraceEventType.Verbose, 0, $"Received { message.MessageTypeId } ({ message.MessageLength } bytes): {message.GetType()}");

            this.MessageReceived?.Invoke(this, new SocketMessageEventArgs(message, handler));
        }
 public ClientNotifEventArgs(int sender, int[] uids, ISocketMessage cmd)
 {
     this.Sender = sender;
     this.Recvs = uids;
     this.Command = cmd;
 }
Example #39
0
        public void SendMessage(ISocketMessage message)
        {
            var data = Serialize(new Parcel(message));

            _pipe.Write(data);
        }