public async Task SendClientNotifyAsync(string socketId, string methodName, object result) { // create the method invocation descriptor. InvocationDescriptor invocationDescriptor = new InvocationDescriptor { MethodName = methodName, Params = result }; WebSocketConnection socket = WebSocketConnectionManager.GetSocketById(socketId); if (socket == null) { return; } var message = new Message() { MessageType = MessageType.MethodInvocation, Data = JsonConvert.SerializeObject(invocationDescriptor) }; await SendMessageAsync(socketId, message).ConfigureAwait(false); }
private async Task Receive(WebSocketConnection socket, Action <WebSocketReceiveResult, string> handleMessage) { while (socket.WebSocket.State == WebSocketState.Open) { ArraySegment <Byte> buffer = new ArraySegment <byte>(new Byte[1024 * 4]); string message = null; WebSocketReceiveResult result = null; try { using (var ms = new MemoryStream()) { do { result = await socket.WebSocket.ReceiveAsync(buffer, CancellationToken.None).ConfigureAwait(false); ms.Write(buffer.Array, buffer.Offset, result.Count); }while (!result.EndOfMessage); ms.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(ms, Encoding.UTF8)) { message = await reader.ReadToEndAsync().ConfigureAwait(false); } } handleMessage(result, message); } catch (WebSocketException e) { if (e.WebSocketErrorCode == WebSocketError.ConnectionClosedPrematurely) { socket.WebSocket.Abort(); } } } await _webSocketHandler.OnDisconnected(socket); }
public async Task SendClientErrorAsync(string socketId, string methodName, RemoteException error) { // create the method invocation descriptor. InvocationResult invocationResult = new InvocationResult { MethodName = methodName, Exception = error }; WebSocketConnection socket = WebSocketConnectionManager.GetSocketById(socketId); if (socket == null) { return; } invocationResult.Id = socket.NextCmdId(); var message = new Message() { MessageType = MessageType.MethodInvocation, Data = JsonConvert.SerializeObject(invocationResult) }; await SendMessageAsync(socketId, message).ConfigureAwait(false); }
public async Task OnReceivedTextAsync(WebSocketConnection socket, string serializedMessage) { InvocationDescriptor invocationDescriptor = null; try { invocationDescriptor = JsonConvert.DeserializeObject <InvocationDescriptor>(serializedMessage); //invocationDescriptor = JsonConvert.DeserializeObject<InvocationDescriptor>(serializedMessage, _jsonSerializerSettings); //invocationDescriptor = JsonConvert.DeserializeObject<InvocationDescriptor>(receivedMessage.Data, _jsonSerializerSettings); if (invocationDescriptor == null) { return; } } catch (Exception ex) { return; } // ignore invalid data sent to the server. // method invocation request. if (invocationDescriptor.Params != null) { // retrieve the method invocation request. // if the unique identifier hasn't been set then the client doesn't want a return value. if (invocationDescriptor.Id == 0) { // invoke the method only. try { await MethodInvocationStrategy.OnInvokeMethodReceivedAsync(socket.Id, invocationDescriptor); } catch (Exception) { // we consume all exceptions. } } else { // invoke the method and get the result. InvocationResult invokeResult; try { // create an invocation result with the results. invokeResult = new InvocationResult() { MethodName = invocationDescriptor.MethodName, Id = invocationDescriptor.Id, Result = await MethodInvocationStrategy.OnInvokeMethodReceivedAsync(socket.Id, invocationDescriptor), Exception = null }; } // send the exception as the invocation result if there was one. catch (Exception ex) { invokeResult = new InvocationResult() { MethodName = invocationDescriptor.MethodName, Id = invocationDescriptor.Id, Result = null, Exception = new RemoteException(ex) }; } string json = JsonConvert.SerializeObject(invokeResult); // send a message to the client containing the result. var message = new Message() { MessageType = MessageType.MethodReturnValue, Data = json //Data = JsonConvert.SerializeObject(invokeResult, _jsonSerializerSettings) }; await SendMessageAsync(socket, message).ConfigureAwait(false); } } else { await OnResponseAsync(socket, serializedMessage); } }
/// <summary> /// Called when a client has disconnected from the server. /// </summary> /// <param name="socket">The web-socket of the client.</param> /// <returns>Awaitable Task.</returns> public virtual async Task OnDisconnected(WebSocketConnection socket) { await WebSocketConnectionManager.RemoveSocket(WebSocketConnectionManager.GetId(socket)).ConfigureAwait(false); }
public async Task <T> InvokeClientMethodAsync <T>(string socketId, string methodName, object[] arguments) { // create the method invocation descriptor. object methodParams = null; if (arguments.Length == 1) { methodParams = arguments[0]; } else { methodParams = arguments; } InvocationDescriptor invocationDescriptor = new InvocationDescriptor { MethodName = methodName, Params = methodParams }; WebSocketConnection socket = WebSocketConnectionManager.GetSocketById(socketId); // generate a unique identifier for this invocation. if (socket == null) { return(default(T)); } invocationDescriptor.Id = socket.NextCmdId(); // Guid.NewGuid(); // add ourselves to the waiting list for return values. TaskCompletionSource <InvocationResult> task = new TaskCompletionSource <InvocationResult>(); // after a timeout of 60 seconds we will cancel the task and remove it from the waiting list. new CancellationTokenSource(1000 * 60).Token.Register(() => { _waitingRemoteInvocations[socketId].Remove(invocationDescriptor.Id); task.TrySetCanceled(); }); if (!_waitingRemoteInvocations.ContainsKey(socketId)) { _waitingRemoteInvocations[socketId] = new Dictionary <long, TaskCompletionSource <InvocationResult> >(); } _waitingRemoteInvocations[socketId].Add(invocationDescriptor.Id, task); // send the method invocation to the client. var message = new Message() { MessageType = MessageType.MethodInvocation, //Data = JsonConvert.SerializeObject(invocationDescriptor, _jsonSerializerSettings) Data = JsonConvert.SerializeObject(invocationDescriptor) }; await SendMessageAsync(socketId, message).ConfigureAwait(false); // wait for the return value elsewhere in the program. InvocationResult result = await task.Task; // ... we just got an answer. // if we have completed successfully: if (task.Task.IsCompleted) { // there was a remote exception so we throw it here. if (result.Exception != null) { throw new Exception(result.Exception.Message); } // return the value. // support null. if (result.Result == null) { return(default(T)); } // cast anything to T and hope it works. return((T)result.Result); } // if we reach here we got cancelled or alike so throw a timeout exception. throw new TimeoutException(); // todo: insert fancy message here. }
public virtual async Task OnReceivedBinaryAsync(WebSocketConnection socket, string receivedMessage) { }
public string GetId(WebSocketConnection socket) { return(_sockets.FirstOrDefault(p => p.Value == socket).Key); }
public void AddSocket(WebSocketConnection socket) { _sockets.TryAdd(socket.Id, socket); }
public void Close(WebSocketConnection socket) { CloseAsync(socket).Wait(); }
public async Task CloseAsync(WebSocketConnection socket) { _sockets.TryRemove(socket.ID, out WebSocketConnection throwAwayValue); await socket.CloseAsync(); }
internal void Add(WebSocketConnection socket) { _sockets.TryAdd(socket.ID, socket); OnOpened(socket); }
public virtual void OnMessage(WebSocketConnection socket, ArraySegment <byte> bytes) { }
public virtual void OnMessage(WebSocketConnection socket, string message) { }
public virtual void OnClosed(WebSocketConnection socket) { }
public virtual void OnOpened(WebSocketConnection socket) { }