echoserver.monkey2 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. #rem
  2. Quick quide to writing TCP client/server apps:
  3. * Server:
  4. 1) Use Socket.Listen to create the server socket.
  5. 2) Use Socket.Accept in a loop to accept new clients.
  6. 3) Use Socket.Send and Socket.Receive to communicate with clients.
  7. * Client:
  8. 1) Use Socket.Connect to connect to the listening server (must already be running!) and create a client socket.
  9. 2) Use Socket.Send and Socket.Receive to communicate with the server.
  10. #end
  11. #Import "<mojox>"
  12. #Import "<mojo>"
  13. #Import "<std>"
  14. Using mojox..
  15. Using mojo..
  16. Using std..
  17. Const HOST:="localhost" 'Note: Use "" for 'public' host?
  18. Const PORT:=40122
  19. Class MyWindow Extends Window
  20. Method New()
  21. New Fiber( Server )
  22. New Fiber( Client )
  23. End
  24. Method Server()
  25. Local server:=Socket.Listen( HOST,PORT )
  26. If Not server print "Server: Failed to create server" ; Return
  27. Print "Server @"+server.Address+" listening"
  28. server.SetOption( "SO_REUSEADDR",1 )
  29. server.SetOption( "TCP_NODELAY",1 )
  30. Repeat
  31. Local socket:=server.Accept()
  32. If Not socket Exit
  33. Print "Server accepted client @"+socket.PeerAddress
  34. Local stream:=New SocketStream( socket )
  35. New Fiber( Lambda()
  36. Repeat
  37. Local line:=stream.ReadSizedString()
  38. If Not line Exit
  39. stream.WriteSizedString( line )
  40. Forever
  41. stream.Close()
  42. End )
  43. Forever
  44. Print "Server:Bye"
  45. server.Close()
  46. End
  47. Method Client()
  48. Fiber.Sleep( .5 )
  49. Local client:=Socket.Connect( HOST,PORT )
  50. If Not client Print "Client: Couldn't connect to server" ; Return
  51. Print "Client @"+client.Address+" connected to server @"+client.PeerAddress
  52. client.SetOption( "TCP_NODELAY",1 )
  53. Local stream:=New SocketStream( client )
  54. For Local i:=0 Until 100
  55. stream.WriteSizedString( "This is a number:"+i )
  56. Print "Reply:"+stream.ReadSizedString()
  57. Next
  58. Print "Client:Bye"
  59. stream.Close()
  60. End
  61. Method OnRender( canvas:Canvas ) Override
  62. Global ticks:=0
  63. ticks+=1
  64. canvas.DrawText( ticks,0,0 )
  65. End
  66. End
  67. Function Main()
  68. New AppInstance
  69. New MyWindow
  70. App.Run()
  71. End