How to write a simple TCP server

I'm interested in network programming. In order to test my understanding of the TCP/IP protocol, I wanted to write a simple TCP client and server.

I read the docs but I don't know which procedures I would need to make it work.

Can anyone point me to some code samples I can study?

I would suggest you follow the tutorial More: Systems Programming with Racket, which walks through the implementation of a web server using the TCP procedures.

1 Like
#lang racket

(module common racket
  (provide send)

  (define (send x out)
    (write x out)
    (flush-output out)))

(module server racket
  (provide server)

  (require (submod ".." common))
  
  #; {PortNumber -> Void}
  ;; read 3 messages from clients, eprint them and sent them back
  (define (server port)
    (define listener (tcp-listen port 30 #true))
    (define-values (in-stream out-stream) (tcp-accept listener))
    (main in-stream out-stream)
    (close-input-port in-stream)
    (close-output-port out-stream))

  #; {InputPort OutputPort -> Void}
  ;; read 3 messages eprint them and sent them back 
  (define (main in-stream out-stream)
    {let while-loop ([i 3])
      (when (> i 0)
        (define the-client-sent (read in-stream))
        (eprintf "server says: the client sent ~a\n" the-client-sent)
        (send `[you sent ,the-client-sent] out-stream)
        (while-loop (- i 1)))}))

(module client racket
  (provide client)

  (require (submod ".." common))

  (define LOCALHOST "127.0.0.1")

  #; {PortNumber [optional-ip-address] -> Void}
  ;; send 'a 'b and 'c to the server's `port` (on at), receeive response, eprint
  (define (client port [at LOCALHOST])
    (define-values (in-stream out-stream) (tcp-connect at port))
    (main in-stream out-stream)
    (close-input-port in-stream)
    (close-output-port out-stream))

  #; {InputPort OutputPort -> Void}
  ;; send 3 messages eprint responses 
  (define (main in-stream out-stream)
    (for ([i '(a b c)])
      (send `[sending ,i] out-stream)
      (eprintf "the client says: ~a\n" (read in-stream)))))

(module+ test
  (require (submod ".." client))
  (require (submod ".." server))

  (thread (λ () (server 12345)))
  (thread (λ () (client 12345))))
4 Likes