void SetupReceiving() { Task.Factory.StartNew( async() => { List <byte[]> buffers = new List <byte[]>(); byte[] bytes = new byte[1024]; buffers.Add(bytes); ArraySegment <byte> buffer = new ArraySegment <byte>(bytes); while (socket.State == WebSocketState.Open) { WebSocketReceiveResult result = null; try { result = await socket.ReceiveAsync(buffer, cts.Token); } catch (WebSocketException wex) { if (ErrorReceiving != null) { ErrorReceiving(wex); } Close(); break; } if (!result.EndOfMessage && buffer.Count == buffer.Array.Length) { bytes = new byte[1024]; buffers.Add(bytes); buffer = new ArraySegment <byte>(bytes); continue; } string data = string.Join("", buffers.Select((c) => Encoding.UTF8.GetString(c).TrimEnd('\0'))); SlackSocketMessage message = null; try { message = JsonConvert.DeserializeObject <SlackSocketMessage>(data, new JavascriptDateTimeConverter()); } catch (JsonSerializationException jsonExcep) { continue; } if (message == null) { continue; } else { HandleMessage(message, data); buffers = new List <byte[]>(); bytes = new byte[1024]; buffers.Add(bytes); buffer = new ArraySegment <byte>(bytes); } } }, cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); }
void HandleMessage(SlackSocketMessage message, string data) { if (callbacks.ContainsKey(message.reply_to)) { callbacks[message.reply_to](data); } else if (routes.ContainsKey(message.type) && routes[message.type].ContainsKey(message.subtype ?? "null")) { object o = null; if (routing.ContainsKey(message.type) && routing[message.type].ContainsKey(message.subtype ?? "null")) { o = JsonConvert.DeserializeObject(data, routing[message.type][message.subtype ?? "null"], new JavascriptDateTimeConverter()); } else { //I believe this method is slower than the former. If I'm wrong we can just use this instead. :D Type t = routes[message.type][message.subtype ?? "null"].Method.GetParameters()[0].ParameterType; o = JsonConvert.DeserializeObject(data, t, new JavascriptDateTimeConverter()); } routes[message.type][message.subtype ?? "null"].DynamicInvoke(o); } else { System.Diagnostics.Debug.WriteLine(string.Format("No valid route for {0} - {1}", message.type, message.subtype ?? "null")); } }
void SetupReceiving() { socket.MessageReceived += (sender, args) => { string data = args.Message; //Console.WriteLine("SlackSocket data = " + data); SlackSocketMessage message = null; try { message = data.Deserialize <SlackSocketMessage>(); } catch (JsonException jsonExcep) { if (ErrorReceivingDesiralization != null) { ErrorReceivingDesiralization(jsonExcep); } } if (message != null) { Task.Run(() => { HandleMessage(message, data); }); } }; }
public void Send(SlackSocketMessage message) { if (message.id == 0) { message.id = Interlocked.Increment(ref currentId); } //socket.Send(JsonConvert.SerializeObject(message)); if (message.type == null) { IEnumerable <SlackSocketRouting> routes = message.GetType().GetCustomAttributes <SlackSocketRouting>(); SlackSocketRouting route = null; foreach (SlackSocketRouting r in routes) { route = r; } if (route == null) { throw new InvalidProgramException("Cannot send without a proper route!"); } else { message.type = route.Type; message.subtype = route.SubType; } } sendingQueue.Push(JsonConvert.SerializeObject(message)); if (Interlocked.CompareExchange(ref currentlySending, 1, 0) == 0) { ThreadPool.QueueUserWorkItem(HandleSending); } }
public void Send <K>(SlackSocketMessage message, Action <K> callback) where K : SlackSocketMessage { int sendingId = Interlocked.Increment(ref currentId); message.id = sendingId; callbacks.Add(sendingId, (c) => { K obj = c.Deserialize <K>(); callback(obj); }); Send(message); }
public void Send <K>(SlackSocketMessage message, Action <K> callback) where K : SlackSocketMessage { int sendingId = Interlocked.Increment(ref currentId); message.id = sendingId; callbacks.Add(sendingId, (c) => { K obj = JsonConvert.DeserializeObject <K>(c, new JavascriptDateTimeConverter()); callback(obj); }); Send(message); }
void HandleMessage(SlackSocketMessage message, string data) { if (callbacks.ContainsKey(message.reply_to)) { callbacks[message.reply_to](data); } else if (message.type != null && routes.ContainsKey(message.type) && routes[message.type].ContainsKey(message.subtype ?? "null")) { try { object o = null; if (routing.ContainsKey(message.type) && routing[message.type].ContainsKey(message.subtype ?? "null")) { o = data.Deserialize(routing[message.type][message.subtype ?? "null"]); } else { //I believe this method is slower than the former. If I'm wrong we can just use this instead. :D Type t = routes[message.type][message.subtype ?? "null"].Method.GetParameters()[0].ParameterType; o = data.Deserialize(t); } routes[message.type][message.subtype ?? "null"].DynamicInvoke(o); } catch (Exception e) { if (ErrorHandlingMessage != null) { ErrorHandlingMessage(e); } Log.Debug(e); throw e; } } else { Log.DebugFormat("No valid route for {0} - {1} with this data: {2}", message.type, message.subtype ?? "null", data); System.Diagnostics.Debug.WriteLine(string.Format("No valid route for {0} - {1}", message.type, message.subtype ?? "null")); if (ErrorHandlingMessage != null) { ErrorHandlingMessage(new InvalidDataException(string.Format("No valid route for {0} - {1}", message.type, message.subtype ?? "null"))); } } }
public void Send(SlackSocketMessage message) { if (message.id == 0) { message.id = Interlocked.Increment(ref currentId); } //socket.Send(JsonConvert.SerializeObject(message)); if (string.IsNullOrEmpty(message.type)) { IEnumerable <SlackSocketRouting> routes = message.GetType().GetTypeInfo().GetCustomAttributes <SlackSocketRouting>(); SlackSocketRouting route = null; foreach (SlackSocketRouting r in routes) { route = r; } if (route == null) { throw new InvalidProgramException("Cannot send without a proper route!"); } else { message.type = route.Type; message.subtype = route.SubType; } } sendingQueue.Push(JsonConvert.SerializeObject(message, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore })); if (Interlocked.CompareExchange(ref currentlySending, 1, 0) == 0) { Task.Factory.StartNew(HandleSending); } }
void SetupReceiving() { Task.Factory.StartNew( async() => { try { List <byte[]> buffers = new List <byte[]>(); byte[] bytes = new byte[1024]; buffers.Add(bytes); ArraySegment <byte> buffer = new ArraySegment <byte>(bytes); while (socket.State == WebSocketState.Open) { WebSocketReceiveResult result = null; try { result = await socket.ReceiveAsync(buffer, cts.Token); } catch (WebSocketException wex) { if (ErrorReceiving != null) { ErrorReceiving(wex); } Log.Debug("SetupReceiving ErrorReceiving", wex); Close(); break; } if (result.MessageType == WebSocketMessageType.Close) { await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); Close(); break; } if (!result.EndOfMessage && buffer.Count == buffer.Array.Length) { bytes = new byte[1024]; buffers.Add(bytes); buffer = new ArraySegment <byte>(bytes); continue; } string data = string.Join(string.Empty, buffers.Select((c) => Encoding.UTF8.GetString(c).TrimEnd('\0'))); SlackSocketMessage message = null; try { message = data.Deserialize <SlackSocketMessage>(); } catch (JsonException jsonExcep) { if (ErrorReceivingDesiralization != null) { ErrorReceivingDesiralization(jsonExcep); } Log.Debug("SetupReceiving ErrorReceivingDesiralization", jsonExcep); continue; } if (message != null) { HandleMessage(message, data); buffers = new List <byte[]>(); bytes = new byte[1024]; buffers.Add(bytes); buffer = new ArraySegment <byte>(bytes); } } } catch (Exception ex) { if (ErrorLoopSocket != null) { ErrorLoopSocket(ex); } Log.Debug("SetupReceiving ErrorLoopSocket", ex); } finally { Close(); } }, cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); }