public List <MessageBag> SentMessages(int skip) { List <MessageBag> listMessage = new List <MessageBag>(); using (var db = DatabaseFactory.OpenDbConnection()) { var msgSend = db.Where <ReceiverMessage>(r => r.UserId == NimbusUser.UserId && r.Status == Model.Enums.MessageType.send && r.Visible == true) .Select(r => db.Where <Message>(m => m.Id == r.MessageId && m.Visible == true).FirstOrDefault()) .Where(msg => msg != null).OrderByDescending(d => d.Date).Skip(15 * skip).Take(15); if (msgSend.Count() > 0) { foreach (var item in msgSend) { var user = db.SelectParam <User>(u => u.Id == item.SenderId).FirstOrDefault(); MessageBag msg = new MessageBag() { ChannelId = item.ChannelId, Date = item.Date, Id = item.Id, Receivers = item.Receivers, SenderId = item.SenderId, Text = item.Text, Title = item.Title, Visible = item.Visible, UserName = user.FirstName + " " + user.LastName, AvatarUrl = user.AvatarUrl, UserReadStatus = true }; listMessage.Add(msg); } } } return(listMessage); }
/// <summary> /// This method converts a message string into a message class. /// </summary> /// <param name="message">Message string.</param> /// <returns>Message class.</returns> public static Message GetMessage(string message) { MessageType messageType = MessageUtils.GetMessageType(message); switch (messageType) { case MessageType.Current: case MessageType.CurrentAggregation: Current current = new Current(); current.Unpack(message); return(current); case MessageType.Trade: Trade trade = new Trade(); trade.Unpack(message); return(trade); case MessageType.LoadComplete: LoadComplete loadComplete = new LoadComplete(); loadComplete.Unpack(message); return(loadComplete); } MessageBag messageBag = new MessageBag(); messageBag.Unpack(message); return(messageBag); }
/// <summary> /// 将服务器端发送一条用户退出的指令,前同时删除掉 /// </summary> private static void SendMessage() { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); string serverIp = config.AppSettings.Settings["ServerIp"].Value; string serverPort = config.AppSettings.Settings["ServerPort"].Value; IPAddress _ipAddress = IPAddress.Parse(serverIp); int _port = Convert.ToInt32(serverPort); try { TcpClient _tcpClient = new TcpClient(); _tcpClient.Connect(_ipAddress, _port); NetworkStream ns = _tcpClient.GetStream(); MessageHead head = new MessageHead((int)MessageType.User, 0, 2); MessageBag bag = new MessageBag(head); bag.BytesBody = Encoding.UTF8.GetBytes(UserID); byte[] buffer = bag.ToBytes(); ns.Write(buffer, 0, buffer.Length); ns.Close(); _tcpClient.Close(); } catch { } }
private async Task ProductSelectionReceivedAsync(IDialogContext context, IAwaitable <Product> result) { var product = await result; BotStateRepository.AddProductToBasket(context, product); context.Done(MessageBag.Of(product, MessageType.ProductOrder)); }
/// <summary> /// 验证用户 /// </summary> private bool CheckUser() { ClientServer _client = new ClientServer(); _client.StartConn(); MessageHead head = new MessageHead((int)KeywordMessageType.User, 0, 1); byte[] bodyBytes = Service.GetBodyBytes(password, Service.DictVersion, Service.ComputerMac); MessageBag bag = new MessageBag(head, bodyBytes); _client.SendMessage(bag); MessageBag recBag = _client.ReceiveMessage(); if (recBag == null) { Debug.Fail("有错"); } string returnVal = _client.AnalyzeResponeMessage(recBag); _client.CloseConn(); if (string.Compare(returnVal, "true") != 0) { errorInfo = returnVal; return(false); } return(true); }
/// <summary> /// 监听客户请求 /// </summary> public void Listen() { ///读取配置文件,获取端口号 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); string serverPort = config.AppSettings.Settings["ServerPort"].Value; incFilePath = Path.Combine(Application.StartupPath, "IncFile"); port = Convert.ToInt32(serverPort); try { listener = new TcpListener(IPAddress.Any, port); listener.Start(); while (true) { TcpClient client = listener.AcceptTcpClient(); NetworkStream stream = client.GetStream(); //接收消息包 MessageBag recBag = ReceiveMessageBag(stream); //解析消息包 AnalyzeMessageBag(stream, recBag); } } catch (Exception ex) { //Debug.Fail(ex.Message); ExceptionRecord.Record(ex.Message + ex.Source + ex.TargetSite + ex.StackTrace); throw; } }
/// <summary> /// 接收消息包 /// </summary> /// <param name="stream"></param> private MessageBag ReceiveMessageBag(NetworkStream stream) { MessageBag bag = null; try { byte[] buffer = Utility.Stream.ReadStream(stream, MessageHead.HeadLength); MessageHead head = MessageHead.Parse(buffer); if (head.BodyLength > 0) { byte[] bytesBody = Utility.Stream.ReadStream(stream, head.BodyLength); bag = new MessageBag(head, bytesBody); } else { bag = new MessageBag(head); } } catch (Exception ex) { ExceptionRecord.Record(ex.Message + ex.Source + ex.TargetSite + ex.StackTrace); throw; } return(bag); }
public void GetMessage() { //接收不同类型的消息包 MessageBag msgBag = ReceiveClientMessage(_ns); //解析不同的消息包,并回应客户端 AnalyzeClientMessage(_ns, msgBag); }
/// <summary> /// 更新词库 /// </summary> public void UpdateWord() { ClientServer _client = new ClientServer(); _client.StartConn(); MessageHead head = new MessageHead((int)KeywordMessageType.Upload, 0, 1); byte[] bodyBytes = Service.GetBodyBytes(Service.SessionId, Service.DictVersion, Service.ComputerMac); MessageBag bag = new MessageBag(head, bodyBytes); _client.SendMessage(bag); MessageBag recBag = _client.ReceiveMessage(); string returnVal = _client.AnalyzeResponeMessage(recBag); if (string.Compare(returnVal, "versionSameOfSuccess") == 0) { //验证成功,版本一样,可上传 MessageHead head2 = new MessageHead((int)KeywordMessageType.Upload, 0, 2); string updateCmd = WordsManager.GetUpdateCmd(); byte[] bytes = Encoding.UTF8.GetBytes(updateCmd); MessageBag bag2 = new MessageBag(head2, bytes); _client.SendMessage(bag2); MessageBag recBag2 = _client.ReceiveMessage(); string recVal = _client.AnalyzeResponeMessage(recBag2); if (string.Compare(recVal, "true") != 0) { Debug.Fail("更新失败!"); } else { MessageBox.Show("更新成功!"); KeywordClear(); } } else if (string.Compare(returnVal, "versionDifferentOfSuccess") == 0) { //验证成功,版本不一样,不可上传 需更新本地词库并显示 WordsManager man = new WordsManager(this); man.ShowNewWordsForm(); } else { if (!string.IsNullOrEmpty(returnVal)) { MessageBox.Show(returnVal); } } _client.CloseConn(); }
public MessageHtmlWrapper MessageHtml(int id) { MessageBag bag = new MessageBag(); using (var db = DatabaseFactory.OpenDbConnection()) { var receiverMsg = db.Where <ReceiverMessage>(r => r.UserId == NimbusUser.UserId && r.MessageId == id && r.Status == Model.Enums.MessageType.received).FirstOrDefault(); if (receiverMsg != null) { var msg = db.Where <Message>(m => m.Id == id).FirstOrDefault(); if (msg == null) { return new MessageHtmlWrapper() { Count = 0 } } ; // .Select(r => // db.Where<Message>(m => m.Id == r.MessageId && m.Visible == true).FirstOrDefault()) // .Where(msg => msg != null); User user = db.SelectParam <User>(u => u.Id == msg.SenderId).FirstOrDefault(); bag.ChannelId = msg.ChannelId; bag.Date = msg.Date; bag.Id = msg.Id; bag.SenderId = msg.SenderId; bag.Text = msg.Text.Length > 100 ? msg.Text.Substring(0, 100) : msg.Text; bag.Title = msg.Title; bag.Visible = msg.Visible; bag.UserName = user.FirstName + " " + user.LastName; bag.AvatarUrl = user.AvatarUrl; bag.UserReadStatus = receiverMsg.UserReadStatus; } else { return(new MessageHtmlWrapper() { Count = 0 }); } } var rz = new RazorTemplate(); string htmlMessage = rz.ParseRazorTemplate <MessageBag> ("~/Website/Views/MessagePartials/MessagePartial.cshtml", bag); return(new MessageHtmlWrapper { Count = 1, Html = htmlMessage }); }
public void message_bag_modify() { var bag = new MessageBag <TestMessage>(); var msg = new TestMessage { Content = 1234 }; bag.Enqueue(msg); Assert.True(bag.Dequeue(out var fromBag)); Assert.True(msg.Equals(fromBag)); }
public MessageHtmlWrapper MessageExpandHtml(int id) { MessageBag message = ExpandMsg(id); var rz = new RazorTemplate(); var sbuilder = new StringBuilder(); sbuilder.Append(rz.ParseRazorTemplate <MessageBag> ("~/Website/Views/MessagePartials/MessageExpandPartial.cshtml", message)); return(new MessageHtmlWrapper { Html = sbuilder.ToString() }); }
/// <summary> /// 发送消息包 /// </summary> /// <param name="stream"></param> /// <param name="bag"></param> private void SendMessageBag(NetworkStream stream, MessageBag bag) { try { byte[] buffer = bag.ToBytes(); stream.Write(buffer, 0, buffer.Length); } catch (Exception ex) { // Debug.Fail(ex.Message); ExceptionRecord.Record(ex.Message + ex.Source + ex.TargetSite + ex.StackTrace); throw; } }
public List <MessageBag> ChannelReceivedMessages(int id = 0, int skip = 0) { List <MessageBag> listMessage = new List <MessageBag>(); using (var db = DatabaseFactory.OpenDbConnection()) { bool idsAllow = db.SelectParam <Role>(r => r.ChannelId == id && (r.IsOwner == true || r.ChannelMagager == true || r.MessageManager == true)) .Exists(r => r.UserId == NimbusUser.UserId); if (idsAllow == true) { //BUG: ReceiverMessage precisa de um datetime para poder ordenar por data. var listMsg = db.Where <ReceiverMessage>(r => r.Status == Model.Enums.MessageType.received && r.Visible == true) .Select(r => db.Where <Message>(m => m.Id == r.MessageId && m.Visible == true && m.ChannelId == id) .FirstOrDefault()) .Where(msg => msg != null).OrderBy(d => d.Date).Skip(15 * skip).Take(15); foreach (var msg in listMsg) { MessageBag bag = new MessageBag(); User user = db.SelectParam <User>(u => u.Id == msg.SenderId).FirstOrDefault(); bag.ChannelId = msg.ChannelId; bag.Date = msg.Date; bag.Id = msg.Id; bag.Receivers = msg.Receivers; bag.SenderId = msg.SenderId; bag.Text = msg.Text; bag.Title = msg.Title; bag.Visible = msg.Visible; bag.UserName = user.FirstName + " " + user.LastName; bag.AvatarUrl = user.AvatarUrl; bag.UserReadStatus = db.Where <ReceiverMessage>(r => r.MessageId == msg.Id) .Select(r => r.UserReadStatus).FirstOrDefault(); listMessage.Add(bag); } } } if (listMessage.Count > 0) { return(listMessage); } else { return(null); } }
public MessageBag GetMessageBag() { var messages = TempData["Messages"] as MessageBag; if (messages != null) { return(messages); } messages = new MessageBag(); TempData["Messages"] = messages; return(messages); }
public MessageBag ExpandMsg(int id) { MessageBag msgBag = new MessageBag(); using (var db = DatabaseFactory.OpenDbConnection()) { using (var trans = db.OpenTransaction(System.Data.IsolationLevel.ReadCommitted)) { try { var message = db.Where <ReceiverMessage>(r => r.UserId == NimbusUser.UserId && r.MessageId == id).FirstOrDefault(); Message msg = new Message(); if (message != null) { msg = db.Where <Message>(m => m.Id == message.MessageId && m.Visible == true).FirstOrDefault(); } if (message != null) { User user = db.SelectParam <User>(u => u.Id == msg.SenderId).FirstOrDefault(); msgBag.ChannelId = msg.ChannelId; msgBag.Date = msg.Date; msgBag.Id = msg.Id; msgBag.SenderId = msg.SenderId; msgBag.Text = msg.Text; msgBag.Receivers = msg.Receivers; msgBag.Title = msg.Title; msgBag.Visible = msg.Visible; msgBag.UserName = user.FirstName + " " + user.LastName; msgBag.AvatarUrl = user.AvatarUrl; msgBag.UserReadStatus = true; } message.UserReadStatus = true; db.Update <ReceiverMessage>(message); trans.Commit(); } catch (Exception) { trans.Rollback(); throw; } } } return(msgBag); }
private async Task ActionSelectionReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> result) { var message = await result; switch (message.Text) { case "1": context.Done(MessageBag.Of("User checked out!", MessageType.Checkout)); break; case "2": context.Done(MessageBag.Of("User canceled!", MessageType.Checkout)); break; } }
/// <summary> /// 发送无消息体的消息到客户端 /// </summary> /// <param name="type"></param> private void ResponseMessage(NetworkStream stream, MessageType type, int state) { try { MessageHead head = new MessageHead((int)type, 0, state); MessageBag bag = new MessageBag(head); byte[] buffer = bag.ToBytes(); stream.Write(buffer, 0, buffer.Length); } catch (Exception e) { ExceptionService.WriteExceptionLog(e); DisposeUserMethod.DeleteUser(); Client.Client.Close(); } }
private async Task ResumeAfterCheckoutDialog(IDialogContext context, IAwaitable <object> result) { var messageObject = await result; MessageBag <string> message = (MessageBag <string>)messageObject; switch (message.Type) { case MessageType.Checkout: await context.PostAsync(message.Content); break; } await RootActions(context); context.Wait(MessageReceived); }
//private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result) //{ // var message = await result; // if (message.Text.Contains("products")) // { // await context.Forward(new ProductDialog(), ResumeAfterProductDialog, message, CancellationToken.None); // } // else if (message.Text.Contains("checkout")) // { // await context.Forward(new CheckoutDialog(), ResumeAfterCheckoutDialog, message, CancellationToken.None); // } // else // { // await context.PostAsync("Welcome, how can we help you?"); // await RootActions(context); // context.Wait(MessageReceivedAsync); // } //} private async Task ResumeAfterProductDialog(IDialogContext context, IAwaitable <object> result) { var messageObject = await result; MessageBag <Product> message = (MessageBag <Product>)messageObject; switch (message.Type) { case MessageType.ProductOrder: await context.PostAsync($"The user ordered the product \"{message.Content}\""); break; } await RootActions(context); context.Wait(MessageReceived); }
/// <summary> /// 处理CGI返回的消息; 接收的是userid,同时在返回一个guid /// </summary> /// <param name="cgiGag"></param> private void DealWithCGIMessage(NetworkStream stream, MessageBag cgiBag) { string userID = Encoding.UTF8.GetString(cgiBag.BytesBody); if (CommonService.RecordUserDic.ContainsKey(userID)) { //如果帐户已存在,则删除,重新创建 CommonService.RecordUserDic.Remove(userID); } string passport = CommonService.CreateNewGuid(); //将其记录在服务器端 CommonService.RecordUserDic.Add(userID, passport); //返回一个新的guid ; MessageHead head = new MessageHead((int)MessageType.User, 0, 3); MessageBag bag = new MessageBag(head); byte[] buffer = bag.ToBytes(); stream.Write(buffer, 0, buffer.Length); }
/// <summary> /// 更新本地词库 /// </summary> private void UpdateLocalWord() { ClientServer _client = new ClientServer(); _client.StartConn(); MessageHead head = new MessageHead((int)KeywordMessageType.Update, 0, 1); byte[] bodyBytes = Service.GetBodyBytes(Service.SessionId, Service.DictVersion, Service.ComputerMac); MessageBag bag = new MessageBag(head, bodyBytes); _client.SendMessage(bag); MessageBag recBag = _client.ReceiveMessage(); string returnVal = _client.AnalyzeResponeMessage(recBag); _client.CloseConn(); WordsManager.UpdateLocalWord(); }
/// <summary> /// 解析客户端发过来的消息包 /// </summary> /// <param name="bag"></param> private void AnalyzeClientMessage(NetworkStream stream, MessageBag bag) { LogService.WriteServerRunLog(LogLevel.Info, "解析来自" + _publisherIP + "的不同类型的消息包"); MessageType type = (MessageType)bag.Head.Type; switch (type) { case MessageType.User: if (bag.Head.State == 1) //处理客户端传来的第一个消息包 { FirstMessageBag firstBag = (FirstMessageBag)bag; DealWithUserMessage(stream, firstBag); } else if (bag.Head.State == 2) //用户退出,用户切换 { string getUserId = Encoding.UTF8.GetString(bag.BytesBody); if (CommonService.RecordUserDic.ContainsKey(getUserId)) { CommonService.RecordUserDic.Remove(getUserId); } } else if (bag.Head.State == 3) //由CGI发送的UserID { DealWithCGIMessage(stream, bag); } break; case MessageType.File: FileMessageBag fileBag = (FileMessageBag)bag; DealWithFileMessage(stream, fileBag); break; default: Debug.Fail("未知在MessageType:" + type); break; } }
public static MessageBag GetPlayerMessages(Player player, int offset) { var inboxLimit = player.DonatorGetsMessagesRewards() ? 500 : 150; var receivedMessages = DomainRegistry.Repository.Find(new GetPlayerReceivedMessages { ReceiverId = player.Id }); var sentMessages = DomainRegistry.Repository.Find(new GetPlayerSentMessages { SenderId = player.Id, Take = 20 }); var receivedMessagesToDelete = receivedMessages.Skip(inboxLimit); // paginate down to first N results var paginator = new Paginator(receivedMessages.Count(), 25); paginator.CurrentPage = offset + 1; receivedMessages = receivedMessages.Skip(paginator.GetSkipCount()).Take(paginator.PageSize).ToList(); var output = new MessageBag { Messages = receivedMessages, SentMessages = sentMessages }; foreach (var message in receivedMessagesToDelete) { DomainRegistry.Repository.Execute(new DeleteMessage { MessageId = message.MessageId, OwnerId = player.Id }); } output.Paginator = paginator; return(output); }
/// <summary> /// 解析返回来的消息包。格式为:sessionId + version + updateCmd /// sessionId 32位 /// version 6位 /// </summary> /// <param name="bag"></param> private void AnalyzeBodyBytes(MessageBag bag) { byte[] bodyBytes = bag.BytesBody; //1.修改sessionId byte[] idByte = new byte[sessionIdLength]; Array.Copy(bodyBytes, 0, idByte, 0, sessionIdLength); Service.SessionId = Encoding.UTF8.GetString(idByte); //2.更新词库,修改词库版本号 byte[] versionByte = new byte[versionLength]; Array.Copy(bodyBytes, sessionIdLength, versionByte, 0, versionLength); Service.DictVersion = Encoding.UTF8.GetString(versionByte); //3更新词库(版本一样,则不需要更新;否则,需要更新) int leg = idByte.Length + versionByte.Length; int bodyLenth = bodyBytes.Length - leg; byte[] body = new byte[bodyLenth]; Array.Copy(bodyBytes, leg, body, 0, bodyLenth); string updateCmd = Encoding.UTF8.GetString(body); Service.UpdateLocalDict(updateCmd); }
public List <MessageBag> ReceivedMessages(int skip) { List <MessageBag> listMessage = new List <MessageBag>(); using (var db = DatabaseFactory.OpenDbConnection()) { var listIdMsg = db.Where <ReceiverMessage>(r => r.UserId == NimbusUser.UserId && r.Status == Model.Enums.MessageType.received && r.Visible == true) .Select(r => db.Where <Message>(m => m.Id == r.MessageId && m.Visible == true).FirstOrDefault()) .Where(msg => msg != null).OrderByDescending(d => d.Date).Skip(15 * skip).Take(15); if (listIdMsg.Count() > 0) { foreach (var msg in listIdMsg) { MessageBag bag = new MessageBag(); User user = db.SelectParam <User>(u => u.Id == msg.SenderId).FirstOrDefault(); bag.ChannelId = msg.ChannelId; bag.Date = msg.Date; bag.Id = msg.Id; bag.SenderId = msg.SenderId; bag.Text = msg.Text.Length > 100? msg.Text.Substring(0, 100) : msg.Text; bag.Title = msg.Title; bag.Visible = msg.Visible; bag.UserName = user.FirstName + " " + user.LastName; bag.AvatarUrl = user.AvatarUrl; bag.UserReadStatus = db.Where <ReceiverMessage>(r => r.UserId == NimbusUser.UserId && r.MessageId == msg.Id) .Select(r => r.UserReadStatus).FirstOrDefault(); listMessage.Add(bag); } } } return(listMessage); }
public MessageBag MessagesFor(string fieldName) { if (!_bags.ContainsKey(fieldName)) { var bag = new MessageBag(fieldName); _bags.Add(fieldName, bag); } return _bags[fieldName]; }
/// <summary> /// 解析消息包 /// </summary> /// <param name="stream"></param> private void AnalyzeMessageBag(NetworkStream stream, MessageBag bag) { KeywordMessageType type = (KeywordMessageType)bag.Head.Type; switch (type) { case KeywordMessageType.None: break; case KeywordMessageType.User: { byte[] body = bag.BytesBody; UserCheck(stream, body, KeywordMessageType.User); break; } case KeywordMessageType.Upload: { int state = bag.Head.State; if (state == 1) { //首次上传校验信息 byte[] body = bag.BytesBody; string val = UserCheck(stream, body, KeywordMessageType.Upload); //引处校验成功后,将等着接收更新字符串 if (!string.IsNullOrEmpty(val) && val == "sameversion") { MessageBag recBag = ReceiveMessageBag(stream); AnalyzeMessageBag(stream, recBag); } } else { //二次传入更新信息 byte[] body = bag.BytesBody; string updateStr = Encoding.UTF8.GetString(body); //更新本地词库 UpdateServerDict(updateStr); //更改服务器版本号,并保存新增文件 string versionR = GetIncVersion(); Service.DictVersion = versionR; string fileName = versionR; //不加扩展名 SaveFile(fileName, updateStr); //返回"版本号与更新字符串" MessageHead head = new MessageHead((int)KeywordMessageType.Upload, 0, 2); string updateCmd = GetUpdateCmd(); byte[] updateBody = GetBodyBytes(Service.DictVersion, updateCmd); MessageBag returnBag = new MessageBag(head, updateBody); SendMessageBag(stream, returnBag); } break; } case KeywordMessageType.Update: { byte[] body = bag.BytesBody; UserCheck(stream, body, KeywordMessageType.Update); break; } default: break; } }
/// <summary> /// 用户验证 /// </summary> /// <param name="body"></param> private string UserCheck(NetworkStream stream, byte[] body, KeywordMessageType msgType) { string resultVal = ""; string all = Encoding.UTF8.GetString(body); string[] arrstr = all.Split(new[] { '&' }, StringSplitOptions.None); passpart = arrstr[0]; version = arrstr[1]; mac = arrstr[2]; int cmd = 0; //验证密码是否正确 //成功,为真;失败为假 string errorInfo = ""; bool value = isSuccess(msgType, passpart, mac, out errorInfo); if (!value) { MessageHead head = new MessageHead((int)msgType, 0, 0); byte[] info = Encoding.UTF8.GetBytes(errorInfo); MessageBag bag = new MessageBag(head, info); SendMessageBag(stream, bag); resultVal = ""; } else { string newId = Service.GetSessionId(); Service.SetSessionId(mac, newId); //验证版本号 if (string.Compare(version, Service.DictVersion) == 0) { if (msgType == KeywordMessageType.Upload) { cmd = 1; } MessageHead head = new MessageHead((int)msgType, cmd, 1); byte[] idBody = Encoding.UTF8.GetBytes(newId); MessageBag bag = new MessageBag(head, idBody); SendMessageBag(stream, bag); resultVal = "sameversion"; } else { if (msgType == KeywordMessageType.Upload) { cmd = 2; } MessageHead head = new MessageHead((int)msgType, cmd, 2); string updateCmd = GetUpdateCmd(); byte[] updateBody = GetBodyBytes(newId, Service.DictVersion, updateCmd); MessageBag bag = new MessageBag(head, updateBody); SendMessageBag(stream, bag); resultVal = ""; } } return(resultVal); }
/// <summary> /// 解析服务器返回的用户验证后的消息包 /// </summary> /// <param name="bag"></param> /// <returns></returns> public string AnalyzeResponeMessage(MessageBag bag) { int state = 0; KeywordMessageType type = (KeywordMessageType)bag.Head.Type; if (type == KeywordMessageType.User || type == KeywordMessageType.Update) { state = bag.Head.State; switch (state) { case 0: //失败 byte[] bytes = bag.BytesBody; return(Encoding.UTF8.GetString(bytes)); case 1: //成功,版本一样 byte[] idBytes = bag.BytesBody; Service.SessionId = Encoding.UTF8.GetString(idBytes); return("true"); case 2: //成功,版本不一样 AnalyzeBodyBytes(bag); return("true"); default: break; } } if (type == KeywordMessageType.Upload) { //1为验证; 2为更新 state = bag.Head.State; if (state == 1) { //0,表失败; 1表成功,并版本号一样; 2表成功,版本号不一样 int cmd = bag.Head.Cmd; switch (cmd) { case 0: byte[] bytes = bag.BytesBody; return(Encoding.UTF8.GetString(bytes)); case 1: //可以上传更新 byte[] idBytes = bag.BytesBody; Service.SessionId = Encoding.UTF8.GetString(idBytes); return("versionSameOfSuccess"); case 2: //更新本地版本,重新显示 AnalyzeBodyBytes(bag); return("versionDifferentOfSuccess"); default: break; } } else //状态为2 ,表示上传更新 { byte[] Bytes = bag.BytesBody; //解析版本号 byte[] versionByte = new byte[versionLength]; Array.Copy(Bytes, 0, versionByte, 0, versionLength); Service.DictVersion = Encoding.UTF8.GetString(versionByte); //更新本地词库的字符串 int leg = versionLength + sessionIdLength; int length = Bytes.Length - versionLength; byte[] bodyBytes = new byte[length]; Array.Copy(Bytes, versionLength, bodyBytes, 0, length); string body = Encoding.UTF8.GetString(bodyBytes); Service.UpdateLocalDict(body); return("true"); //更新本地词库成功 } } return(""); }
/// <summary> /// 发送用户验证消息/发送更新字符串消息 /// </summary> public void SendMessage(MessageBag bag) { byte[] bodybyte = bag.ToBytes(); _stream.Write(bodybyte, 0, bodybyte.Length); }