private void Context_OnManagerChannelMessage(TcpChannelContext context, byte[] data) { MsgCommand msg = (MsgCommand)data[0]; switch (msg) { case MsgCommand.Msg_Pull_Session: this.ProcessPullMainChannel(context); break; case MsgCommand.Msg_Set_Session_Id: this.SetSessionId(context, data); break; case MsgCommand.Msg_Close_Session: this.CloseSession(data); break; case MsgCommand.Msg_MessageData: this.ProcessSendMessage(data); break; default: break; } }
/// <summary> /// handle client until the client disconnect. /// </summary> public void HandleClient(TcpClient client) { new Task(() => { while (client.Connected) { try { NetworkStream stream = client.GetStream(); BinaryWriter writer = new BinaryWriter(stream); BinaryReader reader = new BinaryReader(stream); //get command from client string recived = reader.ReadString(); MsgCommand msg = JsonConvert.DeserializeObject <MsgCommand>(recived); bool res; //execute the command and get the result. string result = this.controller.ExecuteCommand((int)msg.commandID, msg.args, out res); wMutex.WaitOne(); //write back the result to client writer.Write(result); wMutex.ReleaseMutex(); } catch (Exception e) { //close client Console.WriteLine(e.ToString()); if (clientList.Contains(client)) { clientList.Remove(client); } client.Close(); } } }).Start(); }
public Message(Verbindung my_verbindung, Verbindung to_verbindung, MsgCommand command, int sum) { this.my_verbindung = my_verbindung; this.to_verbindung = to_verbindung; this.command = command; this.sum = sum; }
/// <summary> /// 用户登录 /// </summary> /// <param name="msg"></param> /// <param name="Ip"></param> /// <param name="Port"></param> /// <param name="State"></param> private void UserLogin(ClassMsg msg, System.Net.IPAddress Ip, int Port, int State) { RegisterMsg registermsg = (RegisterMsg) new ClassSerializers().DeSerializerBinary(new MemoryStream(msg.Data)); ClassOptionData OptionData = new ClassOptionData(); //创建并引用ClassOptionData MsgCommand msgState = msg.msgCommand; //获取接收消息的命令 String UserName = registermsg.UserName; //登录用户名称 String PassWord = registermsg.PassWord; //用户密码 String vIP = Ip.ToString(); //用户IP地址 SqlDataReader DataReader = OptionData.ExSQLReader("Select * From tb_CurreneyUser Where Name = " + "'" + UserName + "'" + " and PassWord = "******"'" + PassWord + "'"); //在数据库中通过用户名和密码进行查找 DataReader.Read(); //读取查找到的记录 string ID = Convert.ToString(DataReader.GetInt32(0)); //获取第一条记录中的ID字段值 if (DataReader.HasRows) //当DataReader中有记录信息时 { //修改当前记录的标识为上线状态 OptionData.ExSQL("Update tb_CurreneyUser Set Sign = " + Convert.ToString((int)(MsgCommand.Logined)) + ",IP = " + "'" + vIP + "',Port = " + "'" + Port.ToString() + "'" + " Where ID = " + ID); msg.msgCommand = MsgCommand.Logined; //设置为上线命令 msg.SID = ID; //用户ID值 SendMsgToOne(Ip, Port, msg); //将消息返回给发送用户 UpdateUserState(msg, Ip, Port); //更新用户在线状态 } OptionData.Dispose(); UpdateUser();//更新用户列表 }
/// <summary> /// read string from server. /// </summary> public void Read() { Task t = new Task(() => { try { if (this.IsConnected()) { string buffer; NetworkStream stream = TClient.GetStream(); BinaryReader reader = new BinaryReader(stream); rMutex.WaitOne(); buffer = reader.ReadString(); rMutex.ReleaseMutex(); if (buffer != null) { //conver message from string to messag format MsgCommand msg = JsonConvert.DeserializeObject <MsgCommand>(buffer); //invoke the message. CommandRecived?.Invoke(this, msg); } } } catch (Exception readExp) { Console.WriteLine(readExp.ToString()); } }); t.Start(); t.Wait(); }
/// <summary> /// write message to the server. /// </summary> public void Write(MsgCommand msg) { Task t = new Task(() => { try { if (this.IsConnected()) { NetworkStream stream = TClient.GetStream(); BinaryWriter writer = new BinaryWriter(stream); wMutex.WaitOne(); //conver from message format to string. string send = JsonConvert.SerializeObject(msg); writer.Write(send); wMutex.ReleaseMutex(); } } catch (Exception writeExp) { Console.WriteLine(writeExp.ToString()); } }); t.Start(); t.Wait(); }
public MsgInformation WaitForInformation(MsgCommand command, Predicate <MsgInformation> judgeFunc, int timeout = 7) { var signal = new AutoResetEvent(false); var unit = new WaiterUnit { JudgePredicate = judgeFunc, Signal = signal }; lock (_lockObj) { if (UnitsDic.ContainsKey(command.ToGroup)) { UnitsDic[command.ToGroup].Add(unit); } else { UnitsDic.Add(command.ToGroup, new List <WaiterUnit>() { unit }); } } MsgSender.PushMsg(command); signal.WaitOne(timeout * 1000); lock (_lockObj) { unit = UnitsDic[command.ToGroup].FirstOrDefault(u => u.Id == unit.Id); UnitsDic[command.ToGroup].Remove(unit); } return(unit?.ResultInfos.FirstOrDefault()); }
/// <summary> /// the function that is enable when the event of commandRecieved is /// raised. check between two commands - first if it is to add the whole /// logs that occured so far, or update a new log when the GUI is already running /// </summary> /// <param name="sender"></param> /// <param name="m"></param> public void OnCommandRecieved(object sender, MsgCommand m) { //get the list of logs if ((int)m.commandID == (int)(CommandEnum.LogCommand)) { ObservableCollection <string> collection = JsonConvert. DeserializeObject <ObservableCollection <string> >(m.args[0]); //add logs foreach (string log in collection) { string[] logInfo = log.Split(';'); this.m_Logs.Add(new MessageRecievedEventArgs(this.ConvertType(logInfo[1]), logInfo[0])); } } else { //log added after creation. if ((int)m.commandID == (int)CommandEnum.AddLogCommand) { Application.Current.Dispatcher.Invoke(new Action(() => { this.addNewLog(m); })); } } }
/// <summary> /// 更改登录用户 /// </summary> /// <param name="msg"></param> /// <param name="Ip"></param> /// <param name="Port"></param> /// <returns></returns> private ClassMsg UpdateLoginUser(ClassMsg msg, System.Net.IPAddress Ip, int Port) { //RegisterMsg registermsg = (RegisterMsg)new ClassSerializers().DeSerializeBinary(new MemoryStream(msg.Data)); ClassOptionData OptionData = new ClassOptionData(); //创建并引用ClassOptionData MsgCommand msgState = msg.msgCommand; //获取接收消息的命令 String UserName = msg.UserName; //登录用户名称 String PassWord = msg.PassWord; //用户密码 String vIP = Ip.ToString(); //用户IP地址 SqlDataReader DataReader = OptionData.ExSQLReDr("Select * From tb_Gobang Where UserName = "******"'" + UserName + "'" + " and PassWord = "******"'" + PassWord + "'");//在数据库中通过用户名和密码进行查找 if (DataReader.HasRows) { DataReader.Read(); //读取查找到的记录 string ID = Convert.ToString(DataReader.GetInt32(0)); //获取第一条记录中的ID字段值 msg.Fraction = DataReader.GetInt32(5); //获取当前用户的分数 msg.Sex = DataReader.GetInt32(13); //获取当前用户性别 //修改当前记录的标识为上线状态 OptionData.ExSQL("Update tb_Gobang Set State = " + Convert.ToString((int)(MsgCommand.Logined)) + ",IP = " + "'" + vIP + "',Port = " + "'" + Port.ToString() + "'" + " Where ID = " + ID); msg.msgCommand = MsgCommand.Logined; //设置为上线命令 SendMsgToOne(Ip, Port, msg); //将消息返回给发送用户/////--------------------------------//// UpdateUser(); //更新用户列表 } return(msg); }
/// <summary> /// 判断用户是否注册 /// </summary> /// <param msg="ClassMsg"></param> /// <param Ip="System.Net.IPAddress"></param> /// <param Port="int"></param> /// <returns></returns> private bool IfRegisterAt(ClassMsg msg, System.Net.IPAddress Ip, int Port) { bool RegAt = true; //RegisterMsg registermsg = (RegisterMsg)new ClassSerializers().DeSerializeBinary(new MemoryStream(msg.Data)); ClassOptionData OptionData = new ClassOptionData(); MsgCommand Sate = msg.msgCommand; String UserName = msg.UserName; //注册用户的名称 String PassWord = msg.PassWord; //注册用户的密码 String vIP = Ip.ToString(); //注册用户的IP地址 SqlDataReader DataReader; //查找注册用户 DataReader = OptionData.ExSQLReDr("Select * From tb_Gobang where UserName="******"'" + UserName + "'"); if (DataReader.Read()) { RegAt = true; msg.msgCommand = MsgCommand.RegisterAt; //存在注册用户 SendMsgToOne(Ip, Port, msg); //将注册命令返回给注册用户 } else { DataReader = OptionData.ExSQLReDr("Select * From tb_Gobang where IP=" + "'" + Ip.ToString() + "'"); if (DataReader.Read()) { OptionData.ExSQL("Delete tb_Gobang where IP=" + "'" + Ip.ToString() + "'"); } RegAt = false; msg.msgCommand = MsgCommand.Registered;//用户注册结束命令 } return(RegAt); }
/// <summary> /// OnCommandReceived. /// the function that is called when a command is recieved. /// check if is is from type ConfigCommand. if it is -> than get /// the config from server. /// </summary> /// <param name="sender">sender</param> /// <param name="msg">command</param> public void OnCommandRecived(object sender, MsgCommand msg) { //add information if ((int)msg.commandID == (int)CommandEnum.GetConfigCommand) { OutPutDir = msg.args[0]; SourceName = msg.args[1]; LogName = msg.args[2]; TumbNail = msg.args[3]; string[] h = msg.args[4].Split(';'); foreach (string handler in h) { if (!handlers.Contains(handler)) { handlers.Add(handler); } } } else { //removes the give handler if ((int)msg.commandID == (int)CommandEnum.RemoveHandlerCommand) { this.removeHandler(msg); } } }
/// <summary> /// 用户登录 /// </summary> /// <param name="msg"></param> /// <param name="ip"></param> /// <param name="port"></param> /// <param name="state"></param> private void UserLogin(ClassMsg msg, IPAddress ip, int port, int state) { LoginMsg loginmsg = (LoginMsg) new ClassSerializers().DeSerializeBinary(new MemoryStream(msg.Data)); ClassOptionData OptionData = new ClassOptionData(); //创建并引用ClassOptionData MsgCommand msgState = msg.msgCommand; //获取接收消息的命令 String UserName = loginmsg.UserName; //登录用户名称 String PassWord = loginmsg.PassWord; //用户密码 String vIP = ip.ToString(); //用户IP地址 DataTable DataReader = OptionData.ExSQLReDr("Select * From user Where UserAccount = " + "'" + UserName + "'" + " and UserPassWord = "******"'" + PassWord + "'");//在数据库中通过用户名和密码进行查找 if (DataReader.Rows.Count != 0) //当DataReader中有记录信息时 { string ID = DataReader.Rows[0]["UserID"].ToString(); //获取第一条记录中的ID字段值 //修改当前记录的标识为上线状态 OptionData.ExSQL("Update CurreneyUser Set Sign = " + Convert.ToString((int)(MsgCommand.Logined)) + ",IP = " + "'" + vIP + "',Port = " + "'" + port.ToString() + "'" + " Where ID = " + ID); msg.msgCommand = MsgCommand.Logined; //设置为上线命令 msg.SID = ID; //用户ID值 SendMsgToOne(ip, port, msg); //将消息返回给发送用户 UpdateUserState(msg, ip, port); //更新用户在线状态 } else { SendMsgToOne(ip, port, msg); } OptionData.Dispose(); LoadUsrLst(); //UpdateUser();//更新用户列表 }
private void OnMessage(byte[] data) { MsgCommand cmd = (MsgCommand)data[0]; switch (cmd) { case MsgCommand.Msg_Set_Session: this.CreateSession(data); break; case MsgCommand.Msg_Connect_Work: this._clientAgent.ConnectToServer(this._options.ServiceIPEndPoint); break; case MsgCommand.Msg_LogOut: this.LogOut(); break; case MsgCommand.Msg_MessageData: this.ProcessPackage(data); break; case MsgCommand.Msg_Close_Session: this.ProcessSessionClose(data); break; case MsgCommand.Msg_AccessKeyWrong: this.ProcessAccessKeyWrong(); break; } }
private void CommandInvoke(MsgCommand command) { Console.WriteLine(JsonConvert.SerializeObject(command)); var resolver = CommandResolvers.FirstOrDefault(p => p.CommandType == command.Command); resolver?.Resolve(command); }
public static byte[] CommandCopyTo(MsgCommand cmd, byte[] data) { byte[] bytes = new byte[data.Length + 1]; bytes[0] = (byte)cmd; data.CopyTo(bytes, 1); return(bytes); }
public Message(Verbindung verbindung, MsgCommand command, int sum, int neightInformed = 0, string payload = " ") { this.verbindung = verbindung; this.command = command; this.sum = sum; this.payload = payload; this.neightInformed = neightInformed; }
/// <summary> /// RemoveAction. /// a function that send to server MsgCOmmand that say to remove /// handler /// </summary> public void RemoveAction() { string[] args = new string[2]; args[0] = this.HandlerRemove; MsgCommand cmd = new MsgCommand((int)CommandEnum.RemoveHandlerCommand, args); this.m_client.Write(cmd); System.Threading.Thread.Sleep(5); }
/// <summary> /// send the messgae command msg to the given client. /// </summary> public void notifyClient(TcpClient client, MsgCommand msg) { NetworkStream stream = client.GetStream(); BinaryWriter writer = new BinaryWriter(stream); string writeCommand = msg.ToJSON(); wMutex.WaitOne(); writer.Write(writeCommand); wMutex.ReleaseMutex(); }
/// <summary> /// 添加语聊的信息 /// </summary> /// <param RTX="RichTextBox">RichTextBox控件</param> /// <param CUInfo="ClassMsg">发送的信息</param> /// <param MsgSign="MsgCommand">消息命令</param> public void AddMsgText(RichTextBox RTX, ClassMsg CUInfo, MsgCommand MsgSign) { RTX.ReadOnly = true; //设为只读 RTX.ForeColor = Color.SlateGray; //设置字体颜色 RTX.AppendText(CUInfo.UserName); //添加发送信息的用户名 RTX.AppendText("\r\n"); //换行 RTX.AppendText(CUInfo.MsgText); //添加发送的信息 RTX.AppendText("\r\n"); //换行 RTX.ScrollToCaret(); //将信息添加到控件 }
/// <summary> /// 获取玩家的分数 /// </summary> private void GameF(ClassMsg msg, System.Net.IPAddress Ip, int Port, MsgCommand Nsign) { ClassOptionData OptionData = new ClassOptionData(); SqlDataReader DataReader = OptionData.ExSQLReDr("Select Fraction From tb_Gobang where (IP=" + msg.RIP.Trim() + ")"); //查询进入大厅,或开始游戏的对象 DataReader.Read(); //读取玩家信息 msg.Fraction = DataReader.GetInt32(0); //记录用户的IP地址 udpSocket1.Send(Ip, Port, new ClassSerializers().SerializeBinary(msg).ToArray()); }
public static void PushMsg(MsgCommand msg) { msg.Time = DateTime.Now; var callback = $"[{msg.BindAi}][Command] {(msg.ToGroup == 0 ? "私聊" : GroupSettingSvc[msg.ToGroup].Name)} {msg.ToQQ} {msg.Command} {msg.Msg}"; Global.MsgPublish(callback); Global.CommandInfoService.Send(msg, Global.DefaultConfig.CommandQueueName); RestrictorSvc.Cache(msg.BindAi); }
/// <summary> /// remove handler from list /// </summary> /// <param name="msg"> msg</param> public void removeHandler(MsgCommand msg) { Application.Current.Dispatcher.Invoke(new Action(() => { string handler = msg.args[0]; if (handlers.Contains(handler)) { handlers.Remove(handler); } })); }
/// <summary> /// Constructor. init the client from singelton, create new OBservableList /// for logs, sign to event of commandRecieved. /// </summary> public LogModel() { this.client = GuiClient.instanceS; this.m_Logs = new ObservableCollection <MessageRecievedEventArgs>(); this.client.CommandRecived += this.OnCommandRecieved; string[] args = new string[5]; MsgCommand cmd = new MsgCommand((int)CommandEnum.LogCommand, args); //get the logs client.SendAndRecived(cmd); }
public LogsModel() { Logs = new List <Log>(); LogsFilter = new List <Log>(); m_client = GuiClient.instanceS; m_client.CommandRecived += GetInfoFromServer; string[] args = new string[5]; MsgCommand cmd = new MsgCommand((int)CommandEnum.LogCommand, args); //get config information this.m_client.Write(cmd); }
public void Resolve(MsgCommand command) { var stateDic = WSMgr.ClientsDic.ToDictionary(c => c.Key, c => c.Value.IsConnected); var info = new MsgInformation() { Information = InformationType.CommandBack, Msg = JsonConvert.SerializeObject(stateDic), RelationId = command.Id }; WSMgr.PublishInformation(info); }
/// <summary> /// InfoFromServer. /// a function that is called by an event, and contains /// info from server. check if is a config command or remove /// handler command and act accorindgly. /// </summary> /// <param name="sender">server</param> /// <param name="msg">contains command type and args</param> public void InfoFromServer(object sender, MsgCommand msg) { int id = msg.commandID; if (msg.commandID == (int)CommandEnum.GetConfigCommand) { this.SetConfig(msg); } else if (msg.commandID == (int)CommandEnum.RemoveHandlerCommand) { this.canBeRemoved = RemoveHandler(msg); } }
/// <summary> /// returns the list of the current logs of the ImageService as a command converted to string. /// </summary> public string Execute(string[] args, out bool result) { ObservableCollection <string> obs = logService.listOfLogs; //convert list to string string jsonFormat = JsonConvert.SerializeObject(obs); string[] arg = { jsonFormat }; MsgCommand msg = new MsgCommand((int)CommandEnum.LogCommand, arg); //convert command to string string newCommand = JsonConvert.SerializeObject(msg); result = true; return(newCommand); }
/// <summary> /// addLog. /// receive a MsgCommand, extract from it all the info about /// the message, create appropriate log and add it to list. /// </summary> /// <param name="m"></param> public void addLog(MsgCommand m) { MessageRecievedEventArgs cmd = MessageRecievedEventArgs.FromJSON(m.args[0]); Log lg = new Log(Log.ConverToString((int)cmd.Status), cmd.Message); Logs.Add(lg); if (TypeChose != null) { if (TypeChose.Equals(lg.Type)) { LogsFilter.Add(lg); } } }
public bool WithdrawMessage(MsgInformationEx MsgDTO, object[] param) { var msgid = (long)param[0]; var withdrawCommond = new MsgCommand() { Msg = msgid.ToString(), Command = CommandType.WithdrawMessage, ToGroup = MsgDTO.FromGroup, BindAi = MsgDTO.BindAi }; MsgSender.PushMsg(withdrawCommond); return(true); }
public static void SendMessage(TcpSocketSaeaSession session, MsgCommand cmd, byte[] body = null) { if (body == null) { body = new byte[] { 0 } } ; byte[] bytes = new byte[sizeof(Int32) + body.Length + 1]; BitConverter.GetBytes(body.Length + 1).CopyTo(bytes, 0); bytes[4] = (byte)cmd; body.CopyTo(bytes, 5); session.SendAsync(bytes); } }
public NotificationMessageEx(MsgDestination notification, MsgCommand command, params object[] parameters) { Notification = notification; Command = command; Parameters = parameters; }