void conn_OnMessage(object sender, agsXMPP.protocol.client.Message msg) { WSMessage m = msg as WSMessage; if (m.Delay != null) { } }
public override async Task OnMessageDeserialized(WSConnection connection, WSMessage <MessageModel> message) { _logger.LogInformation("accessToken: " + message.AccessToken); UserModel authedUser = _auth.DecodeTokenToUser(message.AccessToken); if (authedUser == null) { await DropConnection(connection, WebSocketCloseStatus.InvalidPayloadData, "authorization failed"); return; } }
private void ws_onMessage(byte[] data) { try { lastMessage = WSMessage.FromBytes(ref data); } catch (Exception exception) { Debug.LogError(exception, this); return; } Debug.Log($"ws_onMessage({lastMessage.ToString()})"); foreach (WSMessageListener listener in messageListeners) { listener.onMessage(lastMessage.Event, lastMessage.Data); } }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { await startReadMessage(async (message, date, deviceId) => { var payload = new WSMessage { IotData = Convert.ToBase64String(message.ToArray()), MessageDate = date.UtcDateTime, DeviceId = deviceId }; var json = JsonSerializer.Serialize(payload); foreach (var webSocket in webSockets) { await webSocket.Item1.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes(json)), WebSocketMessageType.Text, true, disposalTokenSource.Token); } }); Task.WaitAll(receiveHandlers.Select((hnd) => hnd.Item1).ToArray()); }
static void Main(string[] args) { history = new Queue <MessageModel>(); ws = new WebSocket(WS_SERVER_URL); ws.Opened += (sender, args2) => { Console.WriteLine("Connected to server."); }; ws.Closed += (sender, args2) => { Console.WriteLine("Disconnected from server."); }; ws.DataReceived += (sender, args2) => { Console.WriteLine("Something went wrong: " + args2.Data); }; ws.MessageReceived += (sender, data) => { string json = data.Message; WSMessage <MessageModel> message = JsonSerializer.Deserialize <WSMessage <MessageModel> >(json); if (message != null) { PrintMessage(message.Payload); AddToHistory(message.Payload); } }; ws.Error += (sender, args2) => { Console.WriteLine("Something went wrong: " + args2.Exception); }; ws.Open(); PrintHelp(); while (ParseCommand()) { if (ws.State != WebSocketState.Open) { ws.Open(); } } }
public async Task <bool> SendMessageAsync <T>(string login, WSMessage <T> message) { var socket = WebSocketConnectionManager.GetSocketById(login); if (socket == null || socket.State != WebSocketState.Open) { return(false); } var serializedMessage = JsonSerializer.Serialize(message, GPNJsonSerializer.Option()); var encodedMessage = Encoding.UTF8.GetBytes(serializedMessage); await socket.SendAsync(buffer : new ArraySegment <byte>(array: encodedMessage, offset: 0, count: encodedMessage.Length), messageType : WebSocketMessageType.Text, endOfMessage : true, cancellationToken : CancellationToken.None).ConfigureAwait(false); return(true); }
public async Task <(bool, string, Message)> PostAnswerAsync(WebSocketHandler webSocketHandler, Message message, string login) { if (message.GUID.Equals(Guid.Empty)) { return(false, "message.GUID.Equals.Empty", null); } if (message.Date < DateTime.UtcNow.AddDays(-1)) { return(false, "DateTime.Utc.error", null); } if (message.ServiceGuid is null) { message.ServiceGuid = Guid.Empty; } message.IsSending = false; message.JsonData = JsonSerializer.Serialize(message, GPNJsonSerializer.Option()); var(success, error, newData) = await base.PostAsync(message).ConfigureAwait(false); if (!success) { return(false, error, null); } PrepareForClient(message, newData); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed if (webSocketHandler != null && login != null) { var x = WSMessage <Message> .EventNew(message); webSocketHandler.SendMessageAsync(login, x); } #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed return(true, null, message); }
/// <summary> /// 发送文件 /// </summary> /// <param name="toUser">发给谁</param> /// <param name="postedfile">已经上传的文件返回信息</param> public void SendFile(string toUser, PostedFileResp postedfile) { Jid to = new Jid(BuildJid(toUser)); Jid from = new Jid(BuildJid(UserName)); BodyBase[] bodies = new BodyBase[postedfile.entities.Length]; // 构建发送文件的 message 消息 for (int i = 0; i < postedfile.entities.Length; i++) { PostFileEntity entity = postedfile.entities[i]; // 文件类型 img audio string otype = SdkUtils.GetFileType(entity.filename); // 文件的url string ourl = postedfile.uri + "/" + entity.uuid; string osecret = entity.share_secret; string ofilename = entity.filename; /* * 传图片 * ReceivedData: * <message xmlns='jabber:client' from='easemob-demo#[email protected]/webim' * to='easemob-demo#[email protected]' id='124420481838219668' type='chat'> * <body> * {"from":"weigang75","to":"march3","bodies": * [{"type":"img","url":"https://a1.easemob.com/easemob-demo/chatdemoui/chatfiles/cd6f8050-81f7-11e5-a16a-05187e341cb0", * "secret":"zW-AWoH3EeWmJevV5n4Fpkxnnu3e5okMLIhENE0QHaZbvqg5", * "filename":"原生+自定义.jpg", * "thumb":"https://a1.easemob.com/easemob-demo/chatdemoui/chatfiles/cd6f8050-81f7-11e5-a16a-05187e341cb0", * "thumb_secret":"","size":{"width":952,"height":671}}],"ext":{}}</body></message> * * 传语音 * ReceivedData: * <message xmlns='jabber:client' from='easemob-demo#[email protected]/webim' * to='easemob-demo#[email protected]' id='124421298246910356' type='chat'> * <body> * {"from":"weigang75","to":"march3","bodies": * [{"type":"audio", * "url":"https://a1.easemob.com/easemob-demo/chatdemoui/chatfiles/3ec2bb50-81f8-11e5-8e7c-1fa6315dec2d", * "secret":"PsK7WoH4EeWwmIkeyVsexnkK-Rmqu2X_N2qqK9FQYmUkko8W", * "filename":"环信通讯 - 副本.mp3", * "length":3}],"ext":{}}</body></message> * */ // 如果是文件,需要多一些字段 thumb、thumb_secret、size if ("img".Equals(otype)) { bodies[i] = new ImageBody { type = otype, url = ourl, secret = osecret, filename = ofilename, thumb = ourl, thumb_secret = "", size = new ImageSize { width = entity.imageSize.Width, height = entity.imageSize.Height } }; } else if ("audio".Equals(otype)) { bodies[i] = new AudioBody { type = otype, url = ourl, secret = osecret, filename = ofilename }; } else { bodies[i] = new FileBody { type = otype, url = ourl, secret = osecret, filename = ofilename }; } } MsgData data = new MsgData() { from = UserName, to = toUser, bodies = bodies, ext = new { } }; WSMessage msgNode = new WSMessage(to, from); msgNode.Type = MessageType.chat; msgNode.SetBodyData(data); Send(msgNode); }
public void SendTimestampEvent(float timestamp) { WSMessage message = new WSMessage("scrub", Mathf.Round(timestamp).ToString()); wsController.SendMessage(message); }
public void SendAsync(IUserToken userToken, WSMessage message) { base.SendAsync(userToken, SerializeHelper.ProtolBufSerialize(message)); }
public async void SendMessage(WSMessage message) { byte[] data = message.ToBytes(); await webSocket.Send(data); }
private void OnRecieveMessage(WSMessage msg) { var received = msg.Received; var acked = msg.Acked; if (received != null) { //服务器接收到消息 return; } if (acked != null) { //对方接收到消息 return; } MsgData msgdata = msg.GetBodyData(); var delay = msg.Delay; DateTime?sentTime = null; // 说明消息为离线消息,需要获取离线消息的时间 if (delay != null) { sentTime = delay.Stamp; //delay.From; } //msg foreach (var body in msgdata.bodies) { string title = BuildMsgTitle(msgdata.from, sentTime ?? DateTime.Now);// string.Format("<b>{1}</b> [{0}]", DateTime.Now.ToString("HH:mm:ss"), msgdata.from); //edChat.AppendHtml(title, Color.Red); //edChat.AppendNewLine(); switch (body.type) { case "txt": string content = ((TextBody)body).msg; //edChat.AppendHtml(content, Color.Red, HorizontalAlignment.Left); //edChat.AppendNewLine(2); chatBrower.AppendLeftHtml(toUserName, content); //userWeb. break; case "img": RecieveImageMessage((ImageBody)body); break; case "audio": RecieveAudioMessage((AudioBody)body); break; case "loc": RecieveLocationMessage((LocationBody)body); break; case "video": RecieveVideoMessage((VideoBody)body); break; case "file": RecieveFileMessage((FileBody)body); break; default: break; } } }