public void Send(MessageModel Message) { SendStateObject state = new SendStateObject(); state.WorkSocket = _ConSocket; state.extra = Message; MessageBase sendMessage = null; if (Message is TextMessageModel) { sendMessage = new TextChatMessage((TextMessageModel)Message, Model.Username, Model.id); } else if (Message is ImageMessageModel) { sendMessage = new ImageChatMessage((ImageMessageModel)Message, Model.Username, Model.id); } else if (Message is BuzzMessageModel) { sendMessage = new BuzzMessage(Model.Username, Model.id); } string serializedMessage = sendMessage.Serialize(); byte[] byteMessage = Encoding.UTF8.GetBytes(serializedMessage); state.MessageLength = byteMessage.Length; try { state.WorkSocket.BeginSend(byteMessage, 0, state.MessageLength, SocketFlags.None, SendCallback, state); } catch (Exception ex) when(ex is SocketException || ex is NullReferenceException) { throw new NoConnectionException(); } }
private void HandleMessage(string Message) { MessageBase msg = JsonConvert.DeserializeObject <MessageBase>(Message, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }); switch (msg.Type) { case "TextChat": Application.Current.Dispatcher.Invoke(() => Model.CurrentConnection.Messages.Add(new TextMessageModel(((TextChatMessage)msg).Message, false)) ); break; case "ImageChat": ImageChatMessage convertedMessage = (ImageChatMessage)msg; string path = DataService.SaveImage(convertedMessage.Image, msg.id); Application.Current.Dispatcher.Invoke(() => Model.CurrentConnection.Messages.Add(new ImageMessageModel(path, false)) ); break; case "Disconnect": OnDisconnect(); break; case "ChangedUsername": Application.Current.Dispatcher.Invoke(() => { Model.CurrentConnection.Username = ((ChangedUsernameMessage)msg).Sender; }); break; case "Buzz": Application.Current.Dispatcher.Invoke(() => { SystemSounds.Hand.Play(); }); break; default: return; } // TODO: Deseralize and do something with the message }