Advertisement
Guest User

Untitled

a guest
May 30th, 2016
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.36 KB | None | 0 0
  1. package hr.fer.zemris.java.tecaj10.tcp;
  2. import java.awt.Color;
  3. import java.awt.Graphics;
  4. import java.awt.image.BufferedImage;
  5. import java.io.BufferedInputStream;
  6. import java.io.BufferedOutputStream;
  7. import java.io.ByteArrayOutputStream;
  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. import java.io.OutputStream;
  11. import java.net.InetAddress;
  12. import java.net.InetSocketAddress;
  13. import java.net.ServerSocket;
  14. import java.net.Socket;
  15. import java.nio.charset.StandardCharsets;
  16. import java.time.LocalDateTime;
  17. import java.util.ArrayList;
  18. import java.util.List;
  19.  
  20. import javax.imageio.ImageIO;
  21.  
  22.  
  23. public class HTTPServer {
  24.  
  25. public static void main(String[] args) throws IOException {
  26. if(args.length!=1) {
  27. System.out.println("Očekivao sam port");
  28. return;
  29. }
  30.  
  31. int port = Integer.parseInt(args[0]);
  32.  
  33. ServerSocket serverSocket = new ServerSocket();
  34. serverSocket.bind(
  35. new InetSocketAddress((InetAddress)null, port)
  36. );
  37. while(true) {
  38. Socket toClient = serverSocket.accept();
  39. serve(toClient);
  40. }
  41. }
  42.  
  43. private static void serve(Socket toClient) throws IOException {
  44. try {
  45. InputStream cis = new BufferedInputStream(
  46. toClient.getInputStream()
  47. );
  48. OutputStream cos = new BufferedOutputStream(
  49. toClient.getOutputStream()
  50. );
  51.  
  52. byte[] request = readRequest(cis);
  53. if(request==null) {
  54. sendError(cos, 400, "Bad request");
  55. return;
  56. }
  57. String requestStr = new String(
  58. request,
  59. StandardCharsets.US_ASCII
  60. );
  61.  
  62. List<String> headers = extractHeaders(requestStr);
  63. String[] firstLine = headers.isEmpty() ?
  64. null : headers.get(0).split(" ");
  65. if(firstLine==null || firstLine.length != 3) {
  66. sendError(cos, 400, "Bad request");
  67. return;
  68. }
  69.  
  70. String method = firstLine[0].toUpperCase();
  71. if(!method.equals("GET")) {
  72. sendError(cos, 405, "Method Not Allowed");
  73. return;
  74. }
  75.  
  76. String version = firstLine[2].toUpperCase();
  77. if(!version.equals("HTTP/1.1")) {
  78. sendError(cos, 505, "HTTP Version Not Supported");
  79. return;
  80. }
  81.  
  82. String path = firstLine[1];
  83.  
  84. if (path.equals("/tocno-vrijeme")) {
  85. sendDate(cos);
  86. return;
  87. }
  88.  
  89. composeResponse(
  90. cos, path, version,
  91. headers.subList(1, headers.size())
  92. );
  93. } catch (Exception ex) {
  94. System.out.println("Pogreška: " + ex.getMessage());
  95. } finally {
  96. toClient.close();
  97. }
  98. }
  99.  
  100. private static void composeResponse(OutputStream cos,
  101. String path, String version, List<String> headers)
  102. throws IOException {
  103.  
  104. StringBuilder sb = new StringBuilder(
  105. "<html>\r\n" +
  106. " <head>\r\n" +
  107. " <title>Ispis zaglavlja</title>\r\n"+
  108. " </head>\r\n" +
  109. " <body>\r\n" +
  110. " <h1>Informacije o poslanom upitu</h1>\r\n" +
  111. " <p>Zatražen resurs: " + path + "</p>\r\n" +
  112. " <p>Definirane varijable:</p>\r\n" +
  113. " <table border='1'>\r\n");
  114. for(String redak : headers) {
  115. int pos = redak.indexOf(':');
  116. sb.append(" <tr><td>")
  117. .append(redak.substring(0, pos).trim())
  118. .append("</td><td>")
  119. .append(redak.substring(pos+1).trim())
  120. .append("</td></tr>\r\n");
  121. }
  122. sb.append(
  123. " </table>\r\n" +
  124. " </body>\r\n" +
  125. "</html>\r\n");
  126.  
  127. byte[] tijeloOdgovora = sb.toString().getBytes(
  128. StandardCharsets.UTF_8
  129. );
  130. byte[] zaglavljeOdgovora = (version+" 200 OK\r\n" +
  131. "Server: simple java server\r\n"+
  132. "Content-Type: text/html;charset=UTF-8\r\n"+
  133. "Content-Length: "+tijeloOdgovora.length+"\r\n"+
  134. "Connection: close\r\n"+
  135. "\r\n").getBytes(StandardCharsets.US_ASCII);
  136.  
  137. cos.write(zaglavljeOdgovora);
  138. cos.write(tijeloOdgovora);
  139. cos.flush();
  140. }
  141.  
  142. private static void sendError(OutputStream cos,
  143. int statusCode, String statusText) throws IOException {
  144.  
  145. cos.write(
  146. ("HTTP/1.1 "+statusCode+" "+statusText+"\r\n"+
  147. "Server: simple java server\r\n"+
  148. "Content-Type: text/plain;charset=UTF-8\r\n"+
  149. "Content-Length: 0\r\n"+
  150. "Connection: close\r\n"+
  151. "\r\n").getBytes(StandardCharsets.US_ASCII)
  152. );
  153. cos.flush();
  154.  
  155. }
  156.  
  157.  
  158. private static void sendDate(OutputStream cos) throws IOException {
  159.  
  160. BufferedImage bim = new BufferedImage(400, 200, BufferedImage.TYPE_3BYTE_BGR);
  161. Graphics g = bim.createGraphics();
  162.  
  163. g.setColor(new Color(255, 192, 203));
  164. g.fillRect(0, 0, bim.getWidth(), bim.getHeight());
  165.  
  166. LocalDateTime ldt = LocalDateTime.now();
  167. String datum = ldt.toString();
  168.  
  169. g.setColor(Color.blue);
  170. g.drawString(datum, 10, bim.getHeight() - 10);
  171.  
  172. g.dispose();
  173.  
  174. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  175. ImageIO.write(bim, "png", bos);
  176.  
  177. byte[] okteti = bos.toByteArray();
  178.  
  179. cos.write(
  180. ("HTTP/1.1 200 To mi radiiiii\r\n"+
  181. "Server: simple java server\r\n"+
  182. "Content-Type: image/png\r\n"+
  183. "Content-Length: " + okteti.length + "\r\n"+
  184. "Connection: close\r\n"+
  185. "\r\n").getBytes(StandardCharsets.US_ASCII)
  186. );
  187. cos.write(okteti);
  188. cos.flush();
  189.  
  190. }
  191.  
  192. private static List<String> extractHeaders(
  193. String requestHeader) {
  194.  
  195. List<String> headers = new ArrayList<String>();
  196. String currentLine = null;
  197. for(String s : requestHeader.split("\n")) {
  198. if(s.isEmpty()) break;
  199. char c = s.charAt(0);
  200. if(c==9 || c==32) {
  201. currentLine += s;
  202. } else {
  203. if(currentLine != null) {
  204. headers.add(currentLine);
  205. }
  206. currentLine = s;
  207. }
  208. }
  209. if(!currentLine.isEmpty()) {
  210. headers.add(currentLine);
  211. }
  212. return headers;
  213. }
  214.  
  215. private static byte[] readRequest(InputStream is)
  216. throws IOException {
  217.  
  218. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  219. int state = 0;
  220. l: while(true) {
  221. int b = is.read();
  222. if(b==-1) return null;
  223. if(b!=13) {
  224. bos.write(b);
  225. }
  226. switch(state) {
  227. case 0:
  228. if(b==13) { state=1; } else if(b==10) state=4;
  229. break;
  230. case 1:
  231. if(b==10) { state=2; } else state=0;
  232. break;
  233. case 2:
  234. if(b==13) { state=3; } else state=0;
  235. break;
  236. case 3:
  237. if(b==10) { break l; } else state=0;
  238. break;
  239. case 4:
  240. if(b==10) { break l; } else state=0;
  241. break;
  242. }
  243. }
  244. return bos.toByteArray();
  245. }
  246. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement