One of the nice thing about PLT Scheme is that you can write native scheme network apps, rather than having to use FFI to interface with C libraries for the network apps. The nice thing about using native scheme approach is that it works with PLT's threads, unlike FFI, which blocks all PLT threads (and effectively synchronizes the network access). And according to Geoffrey,
FFI also have the disadvantage of having to worry about whether it expects 32-bit or 64-bit pointers.
The challenge with network development though is that we seldom have to do it, so it's hard to know all of the ins and outs of network development. This series of posts will provide a tutorial of doing networking development. The goal is to keep the principles as general as possible so it applies toward other programming languages, but obviously this is a scheme blog.
General Concept
We'll quickly go over the basic network architecture concept for the sake of completeness.
In general, networking involves
clients and
servers interacting with each other by sending information to each other and (if necessary) wait for responses from the other party.
Clients are programs that sends out the
requests, and servers are programs that "fulfill" the requests (and possibly send back a
response). A program can be both a client and a server at the same time.
The information they send each other are serialized to
bytes, which will be reconstructed by the receivers into meaningful representations that they can interpret.
Depending on the nature of the work, clients and servers might only need to send information to each other once and be done (HTTP is one such protocol), but sometimes they need to communicate back and forth to accomplish the task (SMTP is one such protocol), and such situation it might be necessary for the client and the server to keep track of the state in order to manage the work.
So, at a high level architecture, we need to focus on the following in order to do network development:
- manage the connection (initiation, termination, etc)
- serialize and send information to the other party
- receive information from the other party and interpret the meaning (and act accordingly)
- track and manage the state if the protocol requires it
The above applies to all network developments. The specific details and the associated complexity comes down to the specific protocols you are developing.
Let's take a look at what PLT offers to help us handle each of the needs.
Network Connection Management
By default PLT offers network programming in
TCP,
UDP, and
SSL. You can require them into your module:
(require scheme/tcp scheme/udp openssl)
We'll focus on just TCP network development in this tutorial since most network protocols will be TCP-based.
Initiate Connections
If you are developing a client, you can initiate a client connection with: