Advertisement
Guest User

Untitled

a guest
Feb 20th, 2020
965
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.09 KB | None | 0 0
  1. private static void picoServer06() throws Exception {
  2. /*
  3. Nedenfor kan man se at vi kan bruges RES samt læse fra result-filen.
  4. */
  5. //System.out.println("RES:\n" + RES);
  6. //System.out.println("result-filen:\n" + getResourceFileContents("result.tmpl"));
  7. final ServerSocket server = new ServerSocket(8080);
  8. System.out.println("Listening for connection on port 8080 ....");
  9. String root = "pages";
  10. int count = 0;
  11. while (true) { // keep listening (as is normal for a server)
  12. Socket socket = server.accept();;
  13. workingJack.submit(new Runnable() {
  14. @Override
  15. public void run() {
  16. try {
  17. MakeResponseForPico06(count, socket, root);
  18. } catch (IOException ex) {
  19. System.out.println(ex.getMessage());
  20. }
  21. }
  22. });
  23. }
  24. // System.out.println( getFile("adding.html") );
  25.  
  26. }
  27.  
  28. private static void MakeResponseForPico06(int count, Socket socket, String root) throws IOException {
  29. try {
  30. System.out.println("---- reqno: " + count + " ----");
  31. HttpRequest req = new HttpRequest(socket.getInputStream());
  32. String path = req.getPath();
  33. if (path.endsWith(".html") || path.endsWith(".txt")) {
  34. String html = getResourceFileContents(root + path);
  35. String httpResponse = "HTTP/1.1 200 OK\r\n\r\n" + html;
  36. socket.getOutputStream().write(httpResponse.getBytes("UTF-8"));
  37. } else {
  38. workingJack.submit(new Runnable() {
  39. @Override
  40. public void run() {
  41. try {
  42. String res = "";
  43. switch (path) {
  44. case "/addournumbers":
  45. res = addOurNumbers(req);
  46. break;
  47. case "/multiplyournumbers":
  48. res = multiplyOurNumbers(req);
  49. break;
  50. default:
  51. res = "Unknown path: " + path;
  52. }
  53. String httpResponse = "HTTP/1.1 200 OK\r\n\r\n" + res;
  54. socket.getOutputStream().write(httpResponse.getBytes("UTF-8"));
  55. } catch (Exception ex) {
  56. System.out.println("Test: " + ex.getMessage());
  57. }
  58. }
  59. });
  60. }
  61. } catch (Exception ex) {
  62. String httpResponse = "HTTP/1.1 500 Internal error\r\n\r\n"
  63. + "UUUUPS: " + ex.getLocalizedMessage();
  64. socket.getOutputStream().write(httpResponse.getBytes("UTF-8"));
  65. } finally {
  66. if (socket != null) {
  67. socket.close();
  68. }
  69. }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement