TrivialServer.st 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. Object subclass: #TrivialServer
  2. instanceVariableNames: 'os http counter'
  3. category: 'TrivialServer'!
  4. !TrivialServer methodsFor: 'initializing'!
  5. initialize
  6. counter := 0.
  7. os := require value: 'os'.
  8. http := require value: 'http'.
  9. ! !
  10. !TrivialServer methodsFor: 'processing'!
  11. process: aRequest
  12. | hostname httpVersion stream |
  13. counter := counter + 1.
  14. "Calling a method in a js module"
  15. hostname := os hostname.
  16. "Accessing a property of js HTTP request object"
  17. httpVersion := aRequest httpVersion.
  18. stream := String new writeStream.
  19. stream
  20. nextPutAll: '<html><p>Request HTTP version: ', httpVersion, '</p>';
  21. nextPutAll: '<p>OS hostname: ', hostname, '</p>';
  22. nextPutAll: '<p>Number of requests: ', counter asString, '</p></html>'.
  23. ^stream contents
  24. !
  25. start
  26. | block obj |
  27. block := [:req :res || headers |
  28. headers := Dictionary with: 'content-type' -> 'text/html'.
  29. res writeHead: (Array with: 200 with: headers).
  30. res end: (self process: req)].
  31. (http createServer: block)
  32. listen: 1337 host: '127.0.0.1'.
  33. console log: 'TrivialServer running at http://127.0.0.1:1337/'
  34. ! !
  35. !TrivialServer class methodsFor: 'initialization'!
  36. initialize
  37. "We require these Node modules."
  38. !
  39. main
  40. self new start
  41. ! !