RacketNetworkingTCPUDPSockets

Network Programming (TCP/UDP) | Schema Programming Part 27

2.62 min read
Md Nasim SheikhMd Nasim Sheikh
Share:

Racket makes networking surprisingly simple. It treats network connections as standard input/output ports.

Advertisement

A Simple TCP Client

Let's connect to a web server manually (HTTP is just text over TCP!).

#lang racket

(define-values (in out) (tcp-connect "google.com" 80))

(fprintf out "GET / HTTP/1.0\r\n\r\n")
(flush-output out)

(display (port->string in))

A Simple TCP Server

To listen for connections:

(define listener (tcp-listen 12345))

(let loop ()
  (define-values (in out) (tcp-accept listener))
  
  (thread 
   (lambda ()
     (fprintf out "Welcome to Racket Chat!\n")
     (close-output-port out)))
  
  (loop))

Note the use of thread! This ensures our server can handle multiple clients at once.

UDP

Racket also supports UDP for connectionless protocols.

(define udp (udp-open-socket))
(udp-bind! udp #f 5000)
(udp-send-to udp "localhost" 6000 #"Hello UDP")

Advertisement

Summary

With logic similar to file I/O, you can build chat servers, game backends, or custom protocols. Racket's thread efficiency (Part 18) makes it capable of handling thousands of concurrent connections.

Quick Quiz

Which function creates a listening socket for a TCP server?

Md Nasim Sheikh
Written by

Md Nasim Sheikh

Software Developer at softexForge

Verified Author150+ Projects
Published:

You May Also Like