/tutorial/net/multiplex_connection.e

http://github.com/tybor/Liberty · Specman e · 85 lines · 61 code · 8 blank · 16 comment · 1 complexity · 78e64489b201dd41132be1202385725f MD5 · raw file

  1. class MULTIPLEX_CONNECTION
  2. --
  3. -- Handle one connection to the MULTIPLEX_SERVER.
  4. --
  5. -- Each connection is very simple: all the data is sent back (it's an "echo" thing), except when one of the
  6. -- three commands below is issued. A command is a single word written alone on its line. The three commands
  7. -- are:
  8. --
  9. -- bye simply closes the current connection.
  10. --
  11. -- shutdown will stop the server as soon as all the open connections are closed. The server does not
  12. -- accept any new connection.
  13. --
  14. -- halt closes all the open connections and shut the server down.
  15. --
  16. inherit
  17. CONNECTION
  18. redefine
  19. set_io
  20. end
  21. create {MULTIPLEX_SERVER}
  22. make
  23. feature {LOOP_ITEM}
  24. continue is
  25. local
  26. s: STRING
  27. do
  28. ios.read_line
  29. s := ios.last_string
  30. if not s.is_empty then
  31. inspect s
  32. when "shutdown" then
  33. ios.disconnect
  34. server.shutdown
  35. when "halt" then
  36. server.halt
  37. when "bye" then
  38. ios.disconnect
  39. else
  40. std_output.put_integer(id)
  41. std_output.put_string(once ": ")
  42. std_output.put_line(s)
  43. end
  44. end
  45. end
  46. feature {SERVER}
  47. set_io (a_io: like ios) is
  48. -- Called by the server when the connection is initiated. The stream is the socket into which the
  49. -- connection is plugged.
  50. do
  51. Precursor(a_io)
  52. a_io.unset_timeout
  53. a_io.when_disconnect(agent handle_disconnect)
  54. a_io.put_string(once "Hello! There are three commands available:%
  55. % bye, shutdown and halt.%N")
  56. end
  57. feature {}
  58. make (a_server: like server) is
  59. do
  60. counter.increment
  61. id := counter.value
  62. server := a_server
  63. end
  64. handle_disconnect (a_io: like ios) is
  65. require
  66. a_io = ios
  67. done
  68. do
  69. server.connection_done(Current)
  70. end
  71. id: INTEGER
  72. server: MULTIPLEX_SERVER
  73. counter: COUNTER is
  74. once
  75. create Result
  76. end
  77. end