Requesting example code showing echo server
ysangkok opened this issue · 3 comments
What problem are you trying to solve?
I am trying to write a TCP server that replies with whatever it sent to it. I had a look at http.ss to learn how to use gen-server with listen-tcp, but it is a complex file with more than 1200 lines of code.
Proposed solution
This is what I came up with so far (it just writes "echo" to each connection), but it would be nice if there were a documented way of how to write an echo server.
(define (starter)
(define (init)
(printf "init~n")
(listen-tcp "::" 5300 self)
`#(ok ,'())
)
(define (handle-call msg state)
(printf "handle-call~n")
)
(define (handle-cast msg state)
(printf "handle-cast~n")
)
(define (terminate reason state)
(printf "terminate~n")
)
(define (handle-info msg state)
(printf "handle-info~s~n" (display msg))
(match msg
[#(accept-tcp ,_ ,ip ,op)
(put-bytevector-some op #vu8(101 99 104 111)) ;; echo
(flush-output-port op)
`#(no-reply ,'())]
[#(accept-tcp-failed ,_ ,_ ,_)
`#(stop ,msg ,state)]
)
)
(gen-server:start&link `abc)
)
(application:start starter)
(define (handle-info msg state)
(printf "outer handle-info~n")
)
(define (terminate reason state)
(printf "outer terminate~n")
)
(define (handle-call msg state)
(printf "outer handle-call~n")
)
(define (handle-cast msg state)
(printf "outer handle-cast~n")
)
(gen-server:enter-loop '())
Good question. Examples and tutorials are hard. I tried to sketch a quick repository of examples that start with just enough code to send "echo" and close the port. Then, incrementally moves to a working echo application that uses a pair of gen-servers inside an application hierarchy.
Oh my! Thank you so much laqrix, that is very educational! Perfect, just what I wished for! I'll close this issue since it has been resolved.
The example code I provided above was recently added to the Swish repository. Here is a new link. https://github.com/becls/swish/tree/dev/examples/echo-server