Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading.Tasks;
- namespace Httpd
- {
- class Program
- {
- public static List<Lek> lekovi = new List<Lek>();
- public static void StartListening()
- {
- IPAddress ipAddress = IPAddress.Loopback;
- IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 8080);
- // Create a TCP/IP socket.
- Socket serverSocket = new Socket(AddressFamily.InterNetwork,
- SocketType.Stream, ProtocolType.Tcp);
- // Bind the socket to the local endpoint and
- // listen for incoming connections.
- try
- {
- serverSocket.Bind(localEndPoint);
- serverSocket.Listen(10);
- // Start listening for connections.
- while (true)
- {
- Console.WriteLine("Waiting for a connection...");
- // Program is suspended while waiting for an incoming connection.
- Socket socket = serverSocket.Accept();
- Task t = Task.Factory.StartNew(() => Run(socket));
- }
- }
- catch (Exception e)
- {
- Console.WriteLine(e.ToString());
- }
- Console.WriteLine("\nPress ENTER to continue...");
- Console.Read();
- }
- private static void Run(Socket socket)
- {
- NetworkStream stream = new NetworkStream(socket);
- StreamReader sr = new StreamReader(stream);
- StreamWriter sw = new StreamWriter(stream) { NewLine = "\r\n", AutoFlush = true };
- string resource = GetResource(sr);
- if (resource != null)
- {
- if (resource.Equals(""))
- resource = "index.html";
- Console.WriteLine("Request from " + socket.RemoteEndPoint + ": "
- + resource + "\n");
- if (resource.Contains("add?id="))
- {
- string[] lek = resource.Split(new string[] { "id=", "naziv=", "cena=","kolicina=","tip=" }, StringSplitOptions.None);
- string responseText = "HTTP/1.0 200 OK\r\n\r\n";
- sw.Write(responseText);
- var id = GetPropertyValue(lek[1]);
- var naziv = GetPropertyValue(lek[2]);
- var cena = GetPropertyValue(lek[3]);
- var kolicina = GetPropertyValue(lek[4]);
- var tip = GetPropertyValue(lek[5]);
- Console.WriteLine($"Found lek: {id}, Naziv: {naziv}, Tip: {tip}");
- sw.Write("<html><body>");
- if (String.IsNullOrEmpty(id))
- {
- sw.WriteLine(GetAllUsers());
- }
- else
- {
- if (lekovi.Contains(new Lek { Id = id }))
- {
- sw.Write($"<h1>Lek with:{id} already exists.</h1>");
- }
- else
- {
- lekovi.Add(new Lek { Id = id, Naziv = naziv, Cena = cena,Kolicina = kolicina,Tip = tip });
- sw.Write($"<h1>Added Lek with: {id}</h1>");
- sw.WriteLine(GetAllUsers());
- }
- }
- sw.WriteLine("<a href=\"/index.html\">Povratak na pocetnu stranicu</a>");
- sw.WriteLine("</body></html>");
- }
- else if (resource.Contains("find?tip="))
- {
- string responseText = "HTTP/1.0 200 OK\r\n\r\n";
- sw.Write(responseText);
- sw.Write("<html><body>");
- string[] lek = resource.Split(new string[] {"tip=" }, StringSplitOptions.None);
- var tip = GetPropertyValue(lek[1]);
- if (String.IsNullOrEmpty(tip))
- {
- sw.WriteLine(GetAllUsers());
- }
- else
- {
- List<Lek> pomocniLekovi = new List<Lek>();
- foreach (Lek lekic in lekovi)
- {
- if (lekic.Tip.Equals(tip))
- {
- pomocniLekovi.Add(lekic);
- }
- }
- if(pomocniLekovi.Count != 0)
- {
- string result = "<style>table,th,td{border: 1px solid black;}</style>\n";
- result += "<table>\n";
- result += "<th>Id</th>\n";
- result += "<th>Naziv</th>\n";
- result += "<th>Cena</th>\n";
- result += "<th>Kolicina</th>\n";
- result += "<th>Tip</th>\n";
- foreach (Lek lekic in pomocniLekovi)
- {
- result += "<tr>\n";
- result += "<td>" + lekic.Id + "</td>\n";
- result += "<td>" + lekic.Naziv + "</td>\n";
- result += "<td>" + lekic.Cena + "</td>\n";
- result += "<td>" + lekic.Kolicina + "</td>\n";
- result += "<td>" + lekic.Tip + "</td>\n";
- result += "</tr>\n";
- }
- result += "<table>";
- sw.Write(result);
- }
- else
- {
- sw.WriteLine("<h1>NE POSTOJE LEKOVI IZABRANOG TIPA</h1>");
- }
- }
- sw.WriteLine("<a href=\"/index.html\">Povratak na pocetnu stranicu</a>");
- sw.WriteLine("</body></html>");
- }
- else
- {
- SendResponse(resource, socket, sw);
- }
- }
- sr.Close();
- sw.Close();
- stream.Close();
- socket.Shutdown(SocketShutdown.Both);
- socket.Close();
- //return 0;
- }
- private static string GetPropertyValue(string field)
- {
- var newField = field.Split('&')[0];
- newField = Uri.UnescapeDataString(newField);
- newField = newField.Replace("+", " ");
- return newField;
- }
- private static string GetAllUsers()
- {
- string result = "<style>table,th,td{border: 1px solid black;}</style>\n";
- result += "<table>\n";
- result += "<th>Id</th>\n";
- result += "<th>Naziv</th>\n";
- result += "<th>Cena</th>\n";
- result += "<th>Kolicina</th>\n";
- result += "<th>Tip</th>\n";
- if (lekovi.Count == 0)
- {
- result = "<h3> List is empty! </h3>";
- return result;
- }
- foreach (Lek lek in lekovi)
- {
- result += "<tr>\n";
- result += "<td>" + lek.Id +"</td>\n";
- result += "<td>" + lek.Naziv + "</td>\n";
- result += "<td>" + lek.Cena + "</td>\n";
- result += "<td>" + lek.Kolicina + "</td>\n";
- result += "<td>" + lek.Tip + "</td>\n";
- result += "</tr>\n";
- }
- result += "<table>";
- return result;
- }
- private static string GetResource(StreamReader sr)
- {
- string line = sr.ReadLine();
- if (line == null)
- return null;
- String[] tokens = line.Split(' ');
- // prva linija HTTP zahteva: METOD /resurs HTTP/verzija
- // obradjujemo samo GET metodu
- string method = tokens[0];
- if (!method.Equals("GET"))
- {
- return null;
- }
- string rsrc = tokens[1];
- // izbacimo znak '/' sa pocetka
- rsrc = rsrc.Substring(1);
- // ignorisemo ostatak zaglavlja
- string s1;
- while (!(s1 = sr.ReadLine()).Equals(""))
- Console.WriteLine(s1);
- Console.WriteLine("Request: " + line);
- return rsrc;
- }
- private static void SendResponse(string resource, Socket socket, StreamWriter sw)
- {
- // ako u resource-u imamo bilo šta što nije slovo ili cifra, možemo da
- // konvertujemo u "normalan" oblik
- //resource = Uri.UnescapeDataString(resource);
- // pripremimo putanju do našeg web root-a
- resource = "../../../" + resource;
- FileInfo fi = new FileInfo(resource);
- string responseText;
- if (!fi.Exists)
- {
- // ako datoteka ne postoji, vratimo kod za gresku
- responseText = "HTTP/1.0 404 File not found\r\n"
- + "Content-type: text/html; charset=UTF-8\r\n\r\n<b>404 Нисам нашао:"
- + fi.Name + "</b>";
- sw.Write(responseText);
- Console.WriteLine("Could not find resource: " + fi.Name);
- return;
- }
- // ispisemo zaglavlje HTTP odgovora
- responseText = "HTTP/1.0 200 OK\r\nContent-type: text/html; charset=UTF-8\r\n\r\n";
- sw.Write(responseText);
- // a, zatim datoteku
- socket.SendFile(resource);
- }
- public static int Main(String[] args)
- {
- StartListening();
- return 0;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement