Exemplo n.º 1
0
        public override HttpStatusCode Respond(JsonString subject, JsonString response)
        {
            if (subject == null)
            {
                throw new ArgumentNullException("subject");
            }
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }


            bool   isGetRequest;
            string type = JsonString.ParseString(subject.GetTerminal("type", "error"), "error");

            if (type.Equals("get"))
            {
                isGetRequest = true;
            }
            else if (type.Equals("post"))
            {
                isGetRequest = false;
            }
            else
            {
                return(HttpStatusCode.BadRequest);
            }
            int[] positions = ReadPosition(subject);
            if (positions == null)
            {
                return(HttpStatusCode.BadRequest);
            }
            var responseSubject = JsonString.CreateDict();

            {
                responseSubject.AddTerminal("type", JsonString.StringifyString("post"));
                responseSubject.AddTerminal("topic", JsonString.StringifyString("tracker"));
            }
            response.AddJsonString("subject", responseSubject);

            if (isGetRequest)
            {
                return(RespondGet(subject, responseSubject, positions));
            }
            else
            {
                HttpStatusCode status = RespondPost(subject, responseSubject, positions);
                // not only send the result to one recipient but create an update for all clients
                if (status == HttpStatusCode.OK)
                {
                    var update = new JsonString(response);
                    update.RemoveTerminal("requestId");
                    update.AddTerminal("target", "\"all\"");
                    server.PostUpdate(update);
                }
                return(status);
            }
        }
Exemplo n.º 2
0
 private void CreateErrorResponse(JsonString request, JsonString response, HttpStatusCode status)
 {
     // add status code information
     if (response.Type == JsonStringType.Array)
     {
         // unexpected -> give minimal response
         var error = JsonString.CreateDict();
         error.AddTerminal("status", JsonString.Stringify((int)status));
         response.AddJsonString(string.Empty, error);
         return;
     }
     response.AddTerminal("status", JsonString.Stringify((int)status));
     // add the original message to failed updates
     // that way it is easier to recognize the failed operation
     if (response.GetTerminal("requestId", string.Empty).Length == 0)
     {
         response.AddJsonString("request", new JsonString(request));
     }
 }
Exemplo n.º 3
0
        public HttpStatusCode Respond(JsonString subject, JsonString response)
        {
            if (subject == null)
            {
                throw new ArgumentNullException("subject");
            }
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }
            // send the client and server origin ids as subject
            // while the type must be 'get' which is answered with 'post'
            HttpStatusCode status = HttpStatusCode.OK;

            do
            {
                string type = JsonString.ParseString(subject.GetTerminal("type", "error"), "error");
                if (!type.Equals("get"))
                {
                    status = HttpStatusCode.Forbidden;
                    break;
                }
                response.AddTerminal("origin", JsonString.Stringify(serverOrigin));
                var rSubject = JsonString.CreateDict();
                {
                    rSubject.AddTerminal("type", JsonString.StringifyString("post"));
                    rSubject.AddTerminal("topic", JsonString.StringifyString("origin"));
                    var data = JsonString.CreateDict();
                    {
                        data.AddTerminal("serverOrigin", JsonString.Stringify(serverOrigin));
                        data.AddTerminal("clientOrigin", JsonString.Stringify(clientOrigin));
                    }
                    rSubject.AddJsonString("data", data);
                }
                response.AddJsonString("subject", rSubject);
            } while (false);
            return(status);
        }
Exemplo n.º 4
0
        private void Process()
        {
            // wait for clients and process channels and changes
            var resourceListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 9242);
            //var liveListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 9234);
            var liveWire = new LiveWire.LiveWireServer();

            liveWire.Start();
            resourceListener.Start();
            //liveListener.Start();
            Console.WriteLine("Started server on port 9242");
            while (!stopSignal.WaitOne(16))
            {
                liveWire.Process();
                // accept new clients
                if (resourceListener.Pending())
                {
                    var client = resourceListener.AcceptTcpClient();
                    //client.NoDelay = true;
                    //client.ReceiveTimeout = 1;
                    //client.SendTimeout = 1;
                    var baseChannel = new TcpChannel(client);
                    var channel     = new HttpChannel(baseChannel);
                    //var channel = new WebSocketChannel(baseChannel);
                    AddChannelPrototype(channel);
                }
//				if (liveListener.Pending()) {
//					var client = liveListener.AcceptTcpClient();
//					var baseChannel = new TcpChannel(client);
//					var channel = new WebSocketChannel(baseChannel);
//					AddChannelPrototype(channel);
//				}
                List <IWebChannel> toClose = new List <IWebChannel>();
                foreach (var c in channels)
                {
                    c.Process();
                    if (c.State == WebChannelState.InitFailed || c.State == WebChannelState.Closed)
                    {
                        toClose.Add(c);
                        continue;
                    }

                    if (c.AvailableMessageNo > 0)
                    {
                        var wc = c as WebSocketChannel;
                        if (wc != null)
                        {
                            WebSocketMessage message = wc.EmitMessage();
                            string           text    = message.Text;
                            Console.WriteLine("received: " + text);
                            //string updateMsg = "{ 'type': 'request',
                            Console.WriteLine("circling that");
                            //string updateMsg = "{ 'sender': 'minority', 'type': 'config',  'update', 'content': 'sent to update division' }";
                            //Console.WriteLine("sending update: " + updateMsg);
                            //Thread.Sleep(1000);
                            JsonString str = JsonString.Parse(text);
                            str.AddTerminal("text", "tentacles");
                            wc.SendMessage(new WebSocketMessage(str.ToJsonString()));

                            wc.SendMessage(new WebSocketMessage("{\"type\":\"update\", \"subject\":\"content\"  }"));
                        }
                        var hc = c as HttpChannel;
                        if (hc != null)
                        {
                            HttpMessage message = hc.EmitMessage();
                            //Console.WriteLine("message: ");
                            //Console.WriteLine(message.Header.ToString());
                            //Console.WriteLine(Encoding.UTF8.GetString(message.Content));
                            string resource = message.Header.Resource;

                            byte[]     responseContent = new Services.ResourceWireServer().ProvideResource(resource);
                            HttpHeader responseHeader;
                            if (responseContent.Length > 0)
                            {
                                responseHeader = new HttpHeader(HttpMethod.Response, resource, message.Header.Version, HttpStatusCode.OK);

                                if (resource.EndsWith(".js"))
                                {
                                    responseHeader.Fields.Add("Content-Type", "text/javascript; charset=UTF-8");
                                }
                                else if (resource.EndsWith(".html") || resource.Equals("/"))
                                {
                                    responseHeader.Fields.Add("Content-Type", "text/html; charset=UTF-8");
                                }
                                else if (resource.EndsWith(".css"))
                                {
                                    responseHeader.Fields.Add("Content-Type", "text/css; charset=UTF-8");
                                }
                                else if (resource.EndsWith(".ico"))
                                {
                                    responseHeader.Fields.Add("Content-Type", "image/vnd.microsoft.icon");
                                }
                                else if (resource.EndsWith(".svg"))
                                {
                                    responseHeader.Fields.Add("Content-Type", "image/svg+xml");
                                }
                                else
                                {
                                    responseHeader.Fields.Add("Content-Type", "text/plain; charset=UTF-8");
                                }
                                responseHeader.Fields.Add("Content-Encoding", "identity");
                                responseHeader.Fields.Add("Content-Length", string.Format("{0}", responseContent.Length));
                                //responseHeader.Fields.Add("Transfer-Encoding", "identity");
                                responseHeader.Fields.Add("Connection", "close");
                            }
                            else
                            {
                                responseHeader = new HttpHeader(HttpMethod.Response, resource, message.Header.Version, HttpStatusCode.NotFound);
                                responseHeader.Fields.Add("Content-Length", "0");
                                //responseHeader.Fields.Add("Transfer-Encoding", "identity");
                                responseHeader.Fields.Add("Connection", "close");
                            }
                            responseHeader.Fields.Add("Server", "Irseny");
                            responseHeader.Fields.Add("Date", DateTime.UtcNow.ToString());

                            var response = new HttpMessage(responseHeader, responseContent);

                            hc.SendMessage(response);
                            hc.Close();
                        }
                    }
                }
                foreach (IWebChannel c in toClose)
                {
                    c.Close();
                    Console.WriteLine("closed client " + channels.IndexOf(c));
                    channels.Remove(c);
                }
            }
            foreach (var c in channels)
            {
                c.Close();
            }
            resourceListener.Stop();
        }
Exemplo n.º 5
0
        public HttpStatusCode Respond(JsonString subject, JsonString response)
        {
            if (subject == null)
            {
                throw new ArgumentNullException("subject");
            }
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }

            int    sensorStart = -2;
            int    sensorEnd   = 0;
            bool   isGetRequest;
            string type = JsonString.ParseString(subject.GetTerminal("type", "error"), "error");

            if (type.Equals("get"))
            {
                isGetRequest = true;
            }
            else if (type.Equals("post"))
            {
                isGetRequest = false;
            }
            else
            {
                return(HttpStatusCode.BadRequest);
            }

            string position = JsonString.ParseString(subject.GetTerminal("position", "all"), "all");

            if (position.Equals("all"))
            {
                sensorStart = 0;
                sensorEnd   = 15;               // TODO replace with actual capacity
            }
            else
            {
                sensorStart = JsonString.ParseInt(position, -1);
                sensorEnd   = sensorStart;
            }
            if (sensorStart < 0)
            {
                return(HttpStatusCode.NotFound);
            }

            var responseSubject = JsonString.CreateDict();

            responseSubject.AddTerminal("type", JsonString.StringifyString("post"));
            responseSubject.AddTerminal("topic", JsonString.StringifyString("camera"));
            responseSubject.AddTerminal("position", JsonString.StringifyString(position));
            response.AddJsonString("subject", responseSubject);

            if (isGetRequest)
            {
                return(RespondGet(subject, responseSubject, sensorStart, sensorEnd));
            }
            else
            {
                if (sensorStart != sensorEnd)
                {
                    return(HttpStatusCode.BadRequest);
                }
                HttpStatusCode status = RespondPost(subject, responseSubject, sensorStart);
                // not only send the result to one recipient but create an update for all clients
                if (status == HttpStatusCode.OK)
                {
                    var update = new JsonString(response);
                    update.RemoveTerminal("requestId");
                    update.AddTerminal("target", "\"all\"");
                    server.PostUpdate(update);
                }
                return(status);
            }
        }