Example #1
0
        public static void ServerEntryPoint()
        {
            ServerStartCallback?.Invoke();
            _server.Start(ws =>
            {
                ws.OnOpen = () =>
                {
                    R20Logger.WriteLine("TCP client connected.");
                    ClientConnectCallback?.Invoke();
                    _connection = ws;
                    Connected   = true;
                };

                ws.OnClose = () =>
                {
                    R20Logger.WriteLine("TCP client disconnected.");
                    ClientDisconnectCallback?.Invoke();
                    _connection = null;
                    Connected   = false;
                    R20Logger.Close();
                };

                ws.OnMessage = s =>
                {
                    try
                    {
                        JObject jo = JObject.Parse(s);
                        if (jo.ContainsKey("type"))
                        {
                            if (string.Equals("error", jo["type"].Value <string>()))
                            {
                                R20Logger.WriteLine($"[Error] The cliend sends an error code { jo["data"]["code"].Value<string>() }");
                                R20Logger.WriteLine($"[Error] { jo["data"]["message"].Value<string>() }");
                            }

                            if (string.Equals("polled", jo["type"].Value <string>()))
                            {
                                if (_awaitingPoll && int.TryParse(jo["data"]["value"].Value <string>(), out int i))
                                {
                                    _pollResult = i;
                                    _wh.Set();
                                }
                            }
                        }
                        else
                        {
                            R20Logger.WriteLine($"[Warning] Client sent a JSON object without specifying the type!");
                            R20Logger.WriteLine($"[Warning] The JSON was: { s }");
                        }
                    }
                    catch (JsonException) // Not json?
                    {
                        R20Logger.WriteLine($"[Fine] Client sends a message: { s }");
                    }
                };
            });
        }