public async override Task <WebsocketSessionPeer> JoinSession(HttpContext context, string sessionType, string sessionKey) { WebsocketSession targetSession = GetSessionByKey(sessionKey); if (targetSession == null) { targetSession = this.CreateSession(sessionType, sessionKey); } if (targetSession.GetPeers().Count > 0) { throw new Exception("Unable to join Progress session that already has a subscriber."); } WebSocket socket = await context.WebSockets.AcceptWebSocketAsync(); WebsocketSessionPeer peer = targetSession.AddPeer(socket); targetSession.SetAttribute("hostId", peer.Token.PeerId); // alert requester of their own token WebsocketSessionPeerToken hostToken = peer.Token; WebsocketSessionGreeting greeting = new WebsocketSessionGreeting { SessionKey = sessionKey, HostToken = hostToken, Token = peer.Token }; WebsocketSessionMessageResponse greetingResponse = CreateWebsocketResponseMessage(WebsocketSessionMessageType.Greeting, greeting); SendMessage(peer, greetingResponse); return(peer); }
public WebsocketSessionPeer AddPeer(WebSocket socket) { WebsocketSessionPeer peer = new WebsocketSessionPeer(socket); Peers.TryAdd(peer.Token.PeerId, peer); return(peer); }
public virtual async Task ReceiveBinary(string sessionKey, WebsocketSessionPeer sessionPeer, WebSocketReceiveResult result, byte[] buffer) { List <byte> byteList = new List <byte>(sessionPeer.IdAsByteArray); byteList.AddRange(buffer); SendBinaryToPeers(sessionKey, sessionPeer.Socket, byteList.ToArray()); }
public async override Task ReceiveMessage(string sessionKey, WebsocketSessionPeer peer, WebSocketReceiveResult result, byte[] buffer) { WebsocketSessionError error = new WebsocketSessionError { ErrorCode = "WP_001", Message = "Progress Sessions do not expect messages from the client." }; SendMessage(peer.Socket, error); }
public virtual async Task Invoke(HttpContext context) { if (!context.WebSockets.IsWebSocketRequest) { return; } if (!context.Request.Path.HasValue) { return; } string path = context.Request.Path; string[] pathArray = path.Split("/"); string sessionKey = pathArray[1]; if (string.IsNullOrEmpty(sessionKey)) { return; } WebsocketSessionPeer peer = await SessionService.JoinSession(context, "stream", sessionKey); await Receive(peer.Socket, async (result, buffer) => { if (result.MessageType == WebSocketMessageType.Text) { await((WebsocketSessionService)SessionService).ReceiveMessage(sessionKey, peer, result, buffer); return; } else if (result.MessageType == WebSocketMessageType.Binary) { await SessionService.ReceiveBinary(sessionKey, peer, result, buffer); return; } else if (result.MessageType == WebSocketMessageType.Close) { WebsocketSession targetSession = SessionService.GetSessionByKey(sessionKey); string hostId = targetSession.GetAttributeValue <string>("hostId"); // if the host quit, kill the session if (peer.Token.PeerId == hostId) { await SessionService.EndSession(sessionKey); return; } // otherwise, disconnect and alert host that someone has disconnected await targetSession.RemovePeer(peer.Token.PeerId); Models.WebsocketSessionUpdate[] updates = WebsocketSessionService.CreatePeerUpdates(Models.WebsocketSessionUpdateStatus.Disconnect, peer.Token); Models.WebsocketSessionMessageResponse response = WebsocketSessionService.CreateWebsocketResponseMessage(Models.WebsocketSessionMessageType.StatusUpdates, updates); SessionService.SendMessageToPeers(sessionKey, peer.Token.PeerId, response); } }); await _next.Invoke(context); }
public async Task SendMessage(string sessionKey, string socketId, string message) { WebsocketSession session = this.GetSessionByKey(sessionKey); if (session == null) { throw new Exception("Unknown Session requested: " + sessionKey); } WebsocketSessionPeer sessionSocket = session.GetPeerById(socketId); if (sessionSocket == null) { throw new Exception("Unknown Socket requested: " + socketId); } await SendMessage(sessionSocket.Socket, message); }
public override async Task Invoke(HttpContext context) { if (!context.WebSockets.IsWebSocketRequest) { return; } if (!context.Request.Path.HasValue) { return; } string path = context.Request.Path; string[] pathArray = path.Split("/"); string sessionKey = pathArray[1]; if (string.IsNullOrEmpty(sessionKey)) { return; } WebsocketSessionPeer peer = await SessionService.JoinSession(context, "progress", sessionKey); await Receive(peer.Socket, async (result, buffer) => { if (result.MessageType == WebSocketMessageType.Text) { await SessionService.ReceiveMessage(sessionKey, peer, result, buffer); return; } else if (result.MessageType == WebSocketMessageType.Binary) { await SessionService.ReceiveBinary(sessionKey, peer, result, buffer); return; } else if (result.MessageType == WebSocketMessageType.Close) { await SessionService.EndSession(sessionKey); return; } }); await _next.Invoke(context); }
public virtual async Task <WebsocketSessionPeer> JoinSession(HttpContext context, string sessionType, string sessionKey) { WebsocketSession targetSession = GetSessionByKey(sessionKey); if (targetSession == null) { targetSession = this.CreateSession(sessionType, sessionKey); } WebSocket socket = await context.WebSockets.AcceptWebSocketAsync(); WebsocketSessionPeer sessionSocket = targetSession.AddPeer(socket); string hostId = sessionSocket.Token.PeerId; if (targetSession.GetPeers().Count == 1) { targetSession.SetAttribute("hostId", hostId); } else { hostId = targetSession.GetAttributeValue <string>("hostId"); } // alert requester of their own token, the hosts token and other existing peers WebsocketSessionPeerToken hostToken = targetSession.GetPeerById(hostId).Token; WebsocketSessionPeerToken[] participants = targetSession.GetPeers().Where(pair => pair.Value.Token.PeerId != sessionSocket.Token.PeerId).Select(pair => pair.Value.Token).ToArray(); WebsocketSessionGreeting greeting = new WebsocketSessionGreeting { SessionKey = sessionKey, HostToken = hostToken, Token = sessionSocket.Token, Peers = participants }; WebsocketSessionMessageResponse greetingResponse = CreateWebsocketResponseMessage(WebsocketSessionMessageType.Greeting, greeting); SendMessage(sessionSocket, greetingResponse); return(sessionSocket); }
// access the websocket data as a string; (if you JSON serialized, you might want to only override this function // because you'll know that all of your data will be a string that you are going to deserialize; // If you wanted to do something like streaming video via direct byte arrays, you'd want to override the other // "receive" function. public virtual async Task ReceiveMessageString(string sessionKey, WebsocketSessionPeer peer, WebSocketReceiveResult result, string socketMessage) { try { // parse the request to access the data; WebsocketSessionMessageRequest messageRequest = System.Text.Json.JsonSerializer.Deserialize <WebsocketSessionMessageRequest>(socketMessage); if (messageRequest.Type == WebsocketSessionMessageType.Unknown) { messageRequest.Type = WebsocketSessionMessageType.Text; } // process the request and send the response message, if applicable; ProcessMessageRequest(messageRequest, sessionKey, peer); } catch (Exception exception) { WebsocketSessionError error = new WebsocketSessionError() { ErrorCode = "WP_002", Message = "An error occurred while processing the message" }; SendMessage(peer.Socket, error); } }
private Task ProcessMessageRequest(WebsocketSessionMessageRequest request, string sessionKey, WebsocketSessionPeer peer) { // get a reference to the session WebsocketSession session = GetSessionByKey(sessionKey); // handle the different types of messages; string message = ""; switch (request.Type) { case WebsocketSessionMessageType.Introduction: string hostId = session.GetAttributeValue <string>("hostId"); WebsocketSessionPeerToken token = System.Text.Json.JsonSerializer.Deserialize <Models.WebsocketSessionPeerToken>(request.Message); peer.Token.DisplayName = token.DisplayName; peer.Token.IconUrl = token.IconUrl; if (token.PeerId == hostId) { // if host, no need to request access; just grant access; WebsocketSessionUpdate[] updates = CreatePeerUpdates(WebsocketSessionUpdateStatus.AccessGranted, peer.Token); WebsocketSessionMessageResponse hostAlertResponse = CreateWebsocketResponseMessage(WebsocketSessionMessageType.StatusUpdates, updates); SendMessage(sessionKey, hostId, hostAlertResponse); return(Task.CompletedTask); } message = request.Message; break; case WebsocketSessionMessageType.StatusUpdates: case WebsocketSessionMessageType.ByteArray: case WebsocketSessionMessageType.Text: message = request.Message; break; case WebsocketSessionMessageType.Reaction: if (request.TargetMessageId == null) { throw new Exception("Reaction must provide TargetMessageId value."); } break; default: throw new Exception("Unknown Message Type: " + request.Type); } List <WebsocketSessionMessageResponse> messages = session.GetAttributeValue <List <WebsocketSessionMessageResponse> >("messages"); WebsocketSessionMessageResponse messageResponse = new WebsocketSessionMessageResponse() { MessageId = messages.Count, MessageType = request.Type, Message = message, SenderId = peer.Token.PeerId, Recipients = request.Recipients }; messages.Add(messageResponse); if (request.Recipients == null || request.Recipients.Length == 0) { SendMessageToPeers(sessionKey, peer.Token.PeerId, messageResponse); } else { SendMessage(sessionKey, request.Recipients, messageResponse); } return(Task.CompletedTask); }
// access the raw bytes that were sent through the websocket; public virtual async Task ReceiveMessage(string sessionKey, WebsocketSessionPeer sessionPeer, WebSocketReceiveResult result, byte[] buffer) { string message = Encoding.UTF8.GetString(buffer, 0, result.Count); await ReceiveMessageString(sessionKey, sessionPeer, result, message); }
public async Task SendMessage(WebsocketSessionPeer sessionSocket, string message) { await SendMessage(sessionSocket.Socket, message); }
public async Task SendMessage(WebsocketSessionPeer sessionSocket, object value) { string message = JsonSerializer.Serialize(value); await SendMessage(sessionSocket.Socket, message); }
public string GetId(WebsocketSessionPeer socket) { return(Peers.FirstOrDefault(pair => pair.Value == socket).Key); }