ZetCode

Modula-2 TCP/IP sockets

last modified November 27, 2026 Modula-2

A TCP connection is a stream of bytes between two programs. GNU Modula-2 provides the client side in a module of its own, ClientSocket, which ships with its ISO library but is not part of the ISO standard. OpenSocket connects to a host and a port and returns an ordinary ISO channel, so the program writes and reads it with TextIO, as it would a file from the files article. There is no server side.

The article builds a small HTTP client. In GNU Modula-2 15.2 the module has three bugs that a client must work around: lines must end with CR LF, reading past the last byte of a reply hangs, and closing one socket breaks all others. Each is shown where it matters. All examples are compiled with -fiso.

A test server

The examples talk to a web server on the local machine, so the transcripts are the same for every reader. Python's built-in server is enough. It serves the files of a directory, here a single text file with two lines:

$ mkdir www
$ printf 'Modula-2 was designed by Niklaus Wirth.\r\nIt was published in 1978.\r\n' > www/notes.txt
$ python3 -m http.server 8000 --bind 127.0.0.1 --directory www

The server listens on port 8000 of the loopback address and runs until it is stopped with Ctrl+C, so it is started once in a second terminal. The lines of the file end with a carriage return and a line feed, \r\n, as the lines of HTTP itself do; the reason for that comes later.

Opening a connection

OpenSocket takes a channel variable, the host, the port, the usual channel flags and a result variable, like StreamFile.Open does for files.

connect.mod
MODULE connect;

FROM STextIO IMPORT WriteString, WriteLn;
FROM IOChan IMPORT ChanId;
FROM ChanConsts IMPORT OpenResults, read, write, text;
FROM ClientSocket IMPORT OpenSocket, IsSocket, Close;

VAR
  server: ChanId;
  res: OpenResults;

BEGIN
  OpenSocket(server, "127.0.0.1", 8000, read + write + text, res);
  IF res = opened THEN
    WriteString("connected to 127.0.0.1:8000"); WriteLn;
    IF IsSocket(server) THEN
      WriteString("the channel is a socket"); WriteLn
    END;
    Close(server)
  ELSE
    WriteString("cannot connect"); WriteLn
  END
END connect.

The flags ask for reading, writing and text operations. The result is opened when the connection is made. IsSocket tells whether a channel is a socket, and Close ends the connection. The host may be a name or an address; the examples use 127.0.0.1, because the server listens on IPv4 only.

$ gm2 -fiso connect.mod -o connect
$ ./connect
connected to 127.0.0.1:8000
the channel is a socket

A refused connection

A port with no server behind it refuses the connection, and a host name that does not exist cannot be resolved. Both are ordinary situations that a client must handle.

refused.mod
MODULE refused;

FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM IOChan IMPORT ChanId;
FROM ChanConsts IMPORT OpenResults, read, write, text;
FROM ClientSocket IMPORT OpenSocket, Close;

PROCEDURE Try(host: ARRAY OF CHAR; port: CARDINAL);
VAR
  server: ChanId;
  res: OpenResults;
BEGIN
  WriteString(host); WriteString(":"); WriteCard(port, 0);
  OpenSocket(server, host, port, read + write + text, res);
  CASE res OF
    opened: WriteString(" opened"); Close(server)
  | noSuchFile: WriteString(" no server")
  ELSE
    WriteString(" other problem")
  END;
  WriteLn
END Try;

BEGIN
  Try("127.0.0.1", 8000);
  Try("127.0.0.1", 8001);
  Try("no.such.host.invalid", 80)
END refused.

Try prints the result for one host and port. The CASE on the result type OpenResults from ChanConsts has an ELSE, because the type has fifteen values and only two of them are expected here. A refused connection and an unknown host both give noSuchFile, so the module does not tell them apart. The channel is closed only after a successful open.

$ gm2 -fiso refused.mod -o refused
$ ./refused
127.0.0.1:8000 opened
127.0.0.1:8001 no server
no.such.host.invalid:80 no server

Sending a request

An HTTP request is a line with a method, a path and the protocol version, followed by optional header lines and an empty line. The server answers with a status line, its own header lines, an empty line and the content.

status.mod
MODULE status;

FROM STextIO IMPORT WriteString, WriteLn;
FROM IOChan IMPORT ChanId;
FROM ChanConsts IMPORT OpenResults, read, write, text;
FROM ClientSocket IMPORT OpenSocket, Close;
IMPORT TextIO;

VAR
  server: ChanId;
  res: OpenResults;
  line: ARRAY [0..255] OF CHAR;

BEGIN
  OpenSocket(server, "127.0.0.1", 8000, read + write + text, res);
  IF res # opened THEN
    WriteString("cannot connect"); WriteLn;
    HALT(1)
  END;
  TextIO.WriteString(server, "HEAD /notes.txt HTTP/1.0"); TextIO.WriteLn(server);
  TextIO.WriteLn(server);
  TextIO.ReadString(server, line);
  WriteString("status line: "); WriteString(line); WriteLn;
  Close(server)
END status.

The HEAD method asks for the status line and the headers only. HTTP requires CR LF at the end of each line, and on a socket channel TextIO.WriteLn writes exactly that pair. The second WriteLn sends the empty line that ends the request. ReadString reads the first line of the reply up to its line end.

$ gm2 -fiso status.mod -o status
$ ./status
status line: HTTP/1.0 200 OK

Reading the headers

The headers follow the status line, one per line, up to an empty line. Reading them needs a small procedure, because of the way the socket channel finds line ends.

headers.mod
MODULE headers;

FROM STextIO IMPORT WriteString, WriteLn;
FROM IOChan IMPORT ChanId;
FROM ChanConsts IMPORT OpenResults, read, write, text;
FROM ClientSocket IMPORT OpenSocket, Close;
FROM Strings IMPORT Length, Delete;
IMPORT TextIO;

CONST
  LF = 12C;

PROCEDURE ReadLine(cid: ChanId; VAR s: ARRAY OF CHAR);
BEGIN
  TextIO.ReadString(cid, s);
  TextIO.SkipLine(cid);
  IF (Length(s) > 0) AND (s[0] = LF) THEN
    Delete(s, 0, 1)
  END
END ReadLine;

VAR
  server: ChanId;
  res: OpenResults;
  line: ARRAY [0..255] OF CHAR;

BEGIN
  OpenSocket(server, "127.0.0.1", 8000, read + write + text, res);
  IF res # opened THEN
    WriteString("cannot connect"); WriteLn;
    HALT(1)
  END;
  TextIO.WriteString(server, "HEAD /notes.txt HTTP/1.0"); TextIO.WriteLn(server);
  TextIO.WriteLn(server);
  ReadLine(server, line);
  WHILE Length(line) > 0 DO
    WriteString("| "); WriteString(line); WriteLn;
    ReadLine(server, line)
  END;
  Close(server)
END headers.

The socket channel takes the character before a line feed as the line mark. With CR LF, that is the carriage return: ReadString stops before it and SkipLine skips it, but the line feed stays and becomes the first character of the next line. ReadLine removes it. A line that ends with a plain line feed loses its last character instead, which is why the test file uses CR LF. The loop prints lines until the empty one; the server is HTTP/1.0 and sends a Content-Length header with the size of the file.

$ gm2 -fiso headers.mod -o headers
$ ./headers
| HTTP/1.0 200 OK
| Server: SimpleHTTP Python/3.15.2
| Date: Fri, 27 Nov 2026 20:35:24 GMT
| Content-type: text/plain
| Content-Length: 68
| Last-Modified: Fri, 27 Nov 2026 20:35:23 GMT

Reading to the end

A file is read until ReadResult reports endOfInput. An HTTP/1.0 server closes the connection after the reply, so the same loop should work on a socket. In 15.2 it does not.

readall.mod
MODULE readall;

FROM STextIO IMPORT WriteString, WriteLn;
FROM IOChan IMPORT ChanId;
FROM IOConsts IMPORT ReadResults;
FROM ChanConsts IMPORT OpenResults, read, write, text;
FROM ClientSocket IMPORT OpenSocket, Close;
IMPORT TextIO, IOResult;

VAR
  server: ChanId;
  res: OpenResults;
  line: ARRAY [0..255] OF CHAR;

BEGIN
  OpenSocket(server, "127.0.0.1", 8000, read + write + text, res);
  IF res # opened THEN
    WriteString("cannot connect"); WriteLn;
    HALT(1)
  END;
  TextIO.WriteString(server, "GET /notes.txt HTTP/1.0"); TextIO.WriteLn(server);
  TextIO.WriteLn(server);
  LOOP
    TextIO.ReadString(server, line);
    IF IOResult.ReadResult(server) = endOfInput THEN EXIT END;
    WriteString("| "); WriteString(line); WriteLn;
    TextIO.SkipLine(server)
  END;
  WriteString("end of reply"); WriteLn;
  Close(server)
END readall.

Without ReadLine, each line after the first starts with the leftover line feed, so the output has a line break after every |. The real problem is the end: end of reply never appears. Every read in the module looks one character ahead, and at the end of the stream the look-ahead calls read in a loop that never stops, using a full processor core. timeout ends the program after five seconds with status 124. A client must therefore know where the reply ends and never read past it.

$ gm2 -fiso readall.mod -o readall
$ timeout 5 ./readall
| HTTP/1.0 200 OK
| 
Server: SimpleHTTP Python/3.15.2
| 
Date: Fri, 27 Nov 2026 20:35:24 GMT
| 
Content-type: text/plain
| 
Content-Length: 68
| 
Last-Modified: Fri, 27 Nov 2026 20:35:23 GMT
| 

| 
Modula-2 was designed by Niklaus Wirth.
| 
It was published in 1978.
$ echo $?
124

One Close per program

A client often makes several requests, one connection each. The second bug shows up as soon as the first connection is closed.

twice.mod
MODULE twice;

FROM STextIO IMPORT WriteString, WriteLn;
FROM IOChan IMPORT ChanId;
FROM ChanConsts IMPORT OpenResults, read, write, text;
FROM ClientSocket IMPORT OpenSocket, Close;
IMPORT TextIO;

VAR
  server: ChanId;
  res: OpenResults;
  line: ARRAY [0..255] OF CHAR;
  i: CARDINAL;

BEGIN
  FOR i := 1 TO 2 DO
    OpenSocket(server, "127.0.0.1", 8000, read + write + text, res);
    IF res = opened THEN
      TextIO.WriteString(server, "HEAD / HTTP/1.0"); TextIO.WriteLn(server);
      TextIO.WriteLn(server);
      TextIO.ReadString(server, line);
      WriteString(line); WriteLn;
      Close(server)
    END
  END
END twice.

The first request works. The second connection opens, but the first write to it stops the program with "invalid module id"; the message follows the status line directly because the ISO channel holds back the last line mark of the output. When Close frees the data of one socket, it also removes the identifier of the whole ClientSocket module from a table of valid modules, and every later operation on any socket fails that check. A program can therefore close one socket, as its last socket operation. Other connections are left open; the operating system closes them when the program ends.

$ gm2 -fiso twice.mod -o twice
$ ./twice
HTTP/1.0 200 OKEXCEPTIONS.mod:65:56: In RAISE
EXCEPTIONS.mod:65:56:RTdata: invalid module id
$ echo $?
134

A module for requests

Sending a request and reading a line are needed by every remaining example, so they go into a module. Request connects and sends a request without headers, and ReadLine is the procedure from above.

Http.def
DEFINITION MODULE Http;

FROM IOChan IMPORT ChanId;

PROCEDURE Request(host: ARRAY OF CHAR; port: CARDINAL;
                  method, path: ARRAY OF CHAR;
                  VAR server: ChanId): BOOLEAN;
(* connects and sends a request; FALSE if no connection *)

PROCEDURE ReadLine(server: ChanId; VAR s: ARRAY OF CHAR);
(* reads a line ended by CR LF, without the line end *)

END Http.
Http.mod
IMPLEMENTATION MODULE Http;

FROM IOChan IMPORT ChanId;
FROM ChanConsts IMPORT OpenResults, read, write, text;
FROM ClientSocket IMPORT OpenSocket;
FROM Strings IMPORT Length, Delete;
IMPORT TextIO;

CONST
  LF = 12C;

PROCEDURE Request(host: ARRAY OF CHAR; port: CARDINAL;
                  method, path: ARRAY OF CHAR;
                  VAR server: ChanId): BOOLEAN;
VAR
  res: OpenResults;
BEGIN
  OpenSocket(server, host, port, read + write + text, res);
  IF res # opened THEN
    RETURN FALSE
  END;
  TextIO.WriteString(server, method);
  TextIO.WriteString(server, " ");
  TextIO.WriteString(server, path);
  TextIO.WriteString(server, " HTTP/1.0");
  TextIO.WriteLn(server);
  TextIO.WriteLn(server);
  RETURN TRUE
END Request;

PROCEDURE ReadLine(server: ChanId; VAR s: ARRAY OF CHAR);
BEGIN
  TextIO.ReadString(server, s);
  TextIO.SkipLine(server);
  IF (Length(s) > 0) AND (s[0] = LF) THEN
    Delete(s, 0, 1)
  END
END ReadLine;

END Http.

Request returns FALSE when the connection fails, and the caller decides what to do. The module does not close the channel; following the previous section, that is left to the caller.

code.mod
MODULE code;

FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM IOChan IMPORT ChanId;
FROM Strings IMPORT Extract, Length;
FROM WholeStr IMPORT StrToCard, ConvResults;
FROM Http IMPORT Request, ReadLine;

PROCEDURE Check(path: ARRAY OF CHAR);
VAR
  server: ChanId;
  line, digits, reason: ARRAY [0..255] OF CHAR;
  status: CARDINAL;
  res: ConvResults;
BEGIN
  WriteString(path); WriteString(": ");
  IF NOT Request("127.0.0.1", 8000, "HEAD", path, server) THEN
    WriteString("no connection"); WriteLn;
    RETURN
  END;
  ReadLine(server, line);
  Extract(line, 9, 3, digits);
  Extract(line, 13, Length(line), reason);
  StrToCard(digits, status, res);
  IF res # strAllRight THEN
    WriteString("bad status line")
  ELSIF status = 200 THEN
    WriteString("found")
  ELSE
    WriteCard(status, 0); WriteString(" "); WriteString(reason)
  END;
  WriteLn
END Check;

BEGIN
  Check("/notes.txt");
  Check("/missing.txt");
  Check("/")
END code.

Check makes a HEAD request for a path and reads the status line, for example HTTP/1.0 404 File not found. The status code is the three characters at position 9, and the reason text starts at position 13; Extract takes both out and StrToCard converts the code. The connections are not closed. A path of a directory gives 200 as well, because the server returns a listing of the directory.

$ gm2 -fiso -c Http.mod
$ gm2 -fiso code.mod Http.o -o code
$ ./code
/notes.txt: found
/missing.txt: 404 File not found
/: found

Reading the body

The Content-Length header tells how many bytes of content follow the empty line. A client that counts them knows when to stop, which avoids the hang at the end of the stream.

body.mod
MODULE body;

FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM IOChan IMPORT ChanId;
FROM ClientSocket IMPORT Close;
FROM Strings IMPORT Extract, Length, Equal, Capitalize;
FROM WholeStr IMPORT StrToCard, ConvResults;
FROM Http IMPORT Request, ReadLine;

CONST
  Name = "CONTENT-LENGTH: ";

VAR
  server: ChanId;
  line, head: ARRAY [0..255] OF CHAR;
  size, count: CARDINAL;
  res: ConvResults;

BEGIN
  IF NOT Request("127.0.0.1", 8000, "GET", "/notes.txt", server) THEN
    WriteString("no connection"); WriteLn;
    HALT(1)
  END;
  size := 0;
  ReadLine(server, line);
  WHILE Length(line) > 0 DO
    Extract(line, 0, Length(Name), head);
    Capitalize(head);
    IF Equal(head, Name) THEN
      Extract(line, Length(Name), Length(line), head);
      StrToCard(head, size, res)
    END;
    ReadLine(server, line)
  END;
  WriteString("body of "); WriteCard(size, 0); WriteString(" bytes:"); WriteLn;
  count := 0;
  WHILE count < size DO
    ReadLine(server, line);
    WriteString("| "); WriteString(line); WriteLn;
    count := count + Length(line) + 2
  END;
  Close(server)
END body.

Header names are case-insensitive in HTTP, so the program converts the start of each header line to capitals before it compares it with Name. Then it reads body lines and adds their length plus two for CR LF until it has counted size bytes. After the last line the line feed is still unread, so the look-ahead finds a character and nothing hangs. This is the only socket of the program, so it can be closed. A body with plain line feeds or binary data needs IOChan.RawRead instead, which has the same look-ahead problem at the very end.

$ gm2 -fiso body.mod Http.o -o body
$ ./body
body of 68 bytes:
| Modula-2 was designed by Niklaus Wirth.
| It was published in 1978.

Source

The GNU Modula-2 manual

RFC 1945: Hypertext Transfer Protocol -- HTTP/1.0

In this article we have opened TCP connections with ClientSocket, handled refused connections, sent HTTP requests with TextIO, read the status line, the headers and a body of known length, and worked around three bugs of the module in gm2 15.2. The files article covers the channel procedures used here, and the string processing article the Strings procedures that take a reply apart.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Modula-2 tutorials.