2
0

TrivialServer.st 1.3 KB

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