I was trying to send a message from a client to a server, and print the message on the server.
server.rkt:
#lang racket
(define the-listener (tcp-listen 9876))
(define-values (in out) (tcp-accept the-listener))
(displayln (read in))
(tcp-close the-listener)
client.rkt:
#lang racket
(define-values (in out) (tcp-connect "localhost" 9876))
(write "Hello" out)
I ran server.rkt
and then client.rkt
in the terminal. But the server only prints #<eof>
instead of the Hello
message.
Why is that? And how to do it correctly?
You need to flush the output on the client side with flush-output
after sending the message.
Don't forget to cleanly close the ports with close-input-port
and close-output-port
after usage too, on both the client and the server.
Edit: To answer the first part of your question, you get #<eof>
because your client finishes before its output port has been flushed, which closes this output port, and therefore the server receives this end-of-file message (but means "end-of-stream" rather, here), which you can test with eof-object?
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With