private void PackRecv(NetPack pack)
        {
            switch (pack.eventstr)
            {
            case "OK":
            case "当前已存在活动的WebSocket 已为您切换当前Socket":
                //连接成功
                logger("eventhost_connection", "iotq handshake done.");
                logger("eventhost_connection", "hbinterval=" + hbtime + "  sid=" + conn_sid, ConsoleColor.DarkBlue);
                logger("eventhost", "Done.(" + (DateTime.Now - start).ToString() + ")", ConsoleColor.DarkGreen);
                ready = true;
                break;

            case "尚未在线":
                reconnect();
                break;
            }
        }
Esempio n. 2
0
        public void RecvPacket(NetPack pack)
        {
            switch (pack.eventstr)
            {
            case "OnGroupMsgs":           //群消息
                GroupMessageReceiveEventArgs e = new GroupMessageReceiveEventArgs(pack.payload);
                if (e.user.qq != host.qq) //不是自己
                {
                    onGroupMessageReceive.Invoke(this, e);
                }
                else
                {
                    onGroupMessageSendOkay.Invoke(this, e);
                }

                break;

            case "OnFriendMsgs":    //好友私聊
                PrivateMessageReceiveEventArgs ev = new PrivateMessageReceiveEventArgs(pack.payload);
                if (ev.user.qq != host.qq)
                {
                    onPrivateMessageReceive.Invoke(this, ev);
                }

                break;

            case "OnEvents":    //群其它消息
            {
                string eventname = pack.payload.Value <string>("EventName");
                switch (eventname)
                {
                case "ON_EVENT_GROUP_REVOKE":            //消息撤回
                    onGroupMessageRevoke.Invoke(this, new GroupMessageRevokeEventArgs(pack.payload));
                    break;

                case "ON_EVENT_GROUP_SHUT":            //禁言
                    break;

                case "ON_EVENT_GROUP_ADMINSYSNOTIFY":            //加群申请
                    onGroupEnterRequest.Invoke(this, new GroupEnterRequestEventArgs(pack.payload));
                    break;

                case "ON_EVENT_GROUP_JOIN":            //入群成功
                    onGroupMemberIncrease.Invoke(this, new GroupMemberIncreaseEventArgs(pack.payload));
                    break;

                case "ON_EVENT_GROUP_EXIT":            //退群
                    onGroupMemberDecrease.Invoke(this, new GroupMemberDecreaseEventArgs(pack.payload));
                    break;

                case "ON_EVENT_GROUP_ADMIN":            //管理员变更
                    break;

                case "ON_EVENT_FRIEND_ADDED":            //被加好友
                    onFriendAddRequest.Invoke(this, new FriendAddRequestEventArgs(pack.payload));
                    break;

                default:
                    if (!onUnknownEventReceived.Invoke(this, pack))
                    {
                        host.logger("IOTQ_WARN", "Unrecognized subevent name. Ignore the pack..", ConsoleColor.DarkYellow);
                    }

                    break;
                }
            }
            break;

            default:
                if (!onUnknownEventReceived.Invoke(this, pack))
                {
                    host.logger("IOTQ_WARN", "Unrecognized event name.", ConsoleColor.DarkYellow);
                }

                break;
            }
        }
        /// <summary>
        /// IOTQ协议 事件主机
        /// </summary>
        /// <param name="host">目标IP或主机地址</param>
        /// <param name="qq">当前登录的qq</param>
        /// <param name="threadpool">事件发生时用于处理的线程池</param>
        /// <param name="logger">日志管理器,将处理所有日志信息</param>
        /// <param name="buffersize">接收缓冲区大小  过大导致内存浪费,过小导致多次循环接收</param>
        public EventHost(string host, long qq, pThreadPool threadpool, logger_ logger, int buffersize = 1024)
        {
            start           = DateTime.Now;
            this.logger     = logger;
            this.threadpool = threadpool;
            this.host       = host;
            heartbeat       = new Task(() =>
            {
                while (client.State != WebSocketState.Open)
                {
                    Thread.Sleep(500);
                }

                logger("eventhost_connection", "HB manager started.");
                while (!ctoken.IsCancellationRequested)
                {
                    try
                    {
                        logger("eventhost_connection", "<heartbeat> sent");
                        client.SendAsync(Encoding.UTF8.GetBytes("2"), WebSocketMessageType.Text, true, ctoken).Wait();
                        Thread.Sleep(hbtime);
                    }
                    catch (Exception err)
                    {
                        Die();
                        logger("eventhost_fatal", "heartbeat manager crashed:" + err.Message, ConsoleColor.DarkRed);
                        logger("eventhost_fatal", "recovering...");
                        conn(host, logger);
                        Thread.Sleep(1000);
                    }
                }
                logger("eventhost_connection", "HB manager cancelled by token.");
            });
            receiver = new Task(() =>
            {
                while (client.State != WebSocketState.Open)
                {
                    Thread.Sleep(500);
                }

                logger("eventhost_receiver", "started.");
                while (!ctoken.IsCancellationRequested)
                {
                    try
                    {
                        StringBuilder sb = new StringBuilder();
                        Task <WebSocketReceiveResult> t;
                        do
                        {
                            byte[] buffer = new byte[buffersize];
                            t             = client.ReceiveAsync(buffer, ctoken);
                            t.Wait();
                            //logger("eventhost_receiver_debug", "new pack comming in, SIZE=" + t.Result.Count);
                            byte[] bRec = new byte[t.Result.Count];
                            Array.Copy(buffer, bRec, t.Result.Count);
                            sb.Append(Encoding.UTF8.GetString(bRec));

                            /*
                             * if (!t.Result.EndOfMessage)
                             * {
                             *  logger("eventhost_receiver_debug", " - Large pack truncated, receiving next part...", ConsoleColor.DarkBlue);
                             * }
                             */
                        } while (!t.Result.EndOfMessage);
                        if (InitPack.isInitPack(sb.ToString()))
                        {
                            threadpool.submitWorkload(() =>
                            {
                                InitPack i = new InitPack(sb.ToString());
                                onConnectionInit.Invoke(i);
                            });
                        }
                        else
                        {
                            threadpool.submitWorkload(() =>
                            {
                                NetPack packet = new NetPack(sb.ToString());
                                if (packet.code == 3 && (packet.eventstr == null || packet.eventstr.Length < 1))
                                {
                                    //心跳包
                                }
                                else
                                {
                                    onEventTrigger.Invoke(packet);
                                }
                            });
                        }

                        /*
                         * if (pack.IndexOf("[\"OK\"]") > -1)
                         * {
                         *  logger("eventhost_connection", "ready.");
                         *  ready = true;
                         * }
                         * if(pack.IndexOf("[\"当前已存在活动的WebSocket 已为您切换当前Socket\"]") > -1)
                         * {
                         *  logger("eventhost_connection", "TARGET_SWITCHED - ready.");
                         *  ready = true;
                         * }
                         * if (pack.IndexOf("[\"尚未在线\"]") > -1) {
                         *  logger("eventhost_fatal", "Target not online. Will deleberately crash.");
                         *  ready = false;
                         *  throw new Exception("Target not online. Try again later.");
                         * }
                         */
                        //logger("eventhost_receiver", "pack=" + pack);
                    }
                    catch (Exception err)
                    {
                        Die();
                        logger("eventhost_fatal", "main receiver crashed:" + err.Message, ConsoleColor.DarkRed);
                        logger("eventhost_fatal", "recovering...");
                        conn(host, logger);
                        Thread.Sleep(500);
                    }
                }
                logger("eventhost_receiver", "cancelled by ctoken.", ConsoleColor.DarkBlue);
            });
            this.qq = qq;
            conn(host, logger);
            onConnectionInit += ConnectionInit;
            onEventTrigger   += PackRecv;
            if (heartbeat.Status != TaskStatus.Running)
            {
                heartbeat.Start();
            }

            if (receiver.Status != TaskStatus.Running)
            {
                receiver.Start();
            }
        }