Sockets
HTTP is built on top of simpler connections called sockets. This lesson builds a tiny TCP server and client in one program and has them talk, line by line.
What you will learn#
- what an address, a port, TCP and a socket are,
TcpListener(the server) andTcpClient(the client),- streams, readers and writers over a connection,
- the order in which a conversation happens.
Words#
| Word | Meaning |
|---|---|
| IP address | the address of a computer: 127.0.0.1 means this computer |
| port | a number (0–65535) that says which program on that computer |
| TCP | a reliable connection: bytes arrive in order, none lost |
| socket | one end of a connection |
| listener | a program that waits for others to connect |
The program#
# sockets - a TCP server and client in one program
load "dotnet.ring"
using {
"System.IO"
"System.Net"
"System.Net.Sockets"
}
func main
# STEP 1. The server: a listener waits for connections on a port of this computer.
oListener = new TcpListener(new IPAddress().Loopback,0) # port 0: any free port
oListener.Start(NULL)
nPort = oListener.LocalEndpoint.Port
? "STEP 1: the server listens on 127.0.0.1, port is chosen: " + (nPort > 0)
# STEP 2. The client connects. The connection is accepted by the operating system at once.
oClient = new TcpClient()
oClient.Connect([ :hostname = "127.0.0.1", :port = nPort ])
? "STEP 2: the client is connected: " + oClient.Connected
# STEP 3. The server accepts the waiting connection. Each side gets a stream to read and write.
oAccepted = oListener.AcceptTcpClient()
oServerStream = oAccepted.GetStream()
oClientStream = oClient.GetStream()
oServerReader = new StreamReader(oServerStream)
oServerWriter = new StreamWriter(oServerStream)
oServerWriter.AutoFlush = True
oClientReader = new StreamReader(oClientStream)
oClientWriter = new StreamWriter(oClientStream)
oClientWriter.AutoFlush = True # send every line at once
? "STEP 3: the server accepted the connection"
# STEP 4. A conversation: the client sends a line, the server answers with the same line in upper case
? nl + "STEP 4: three messages"
for cMessage in ["hello","how are you","bye"]
oClientWriter.WriteLine(cMessage) # client -> server
cReceived = oServerReader.ReadLine()
oServerWriter.WriteLine("echo: " + upper(cReceived)) # server -> client
? " sent '" + cMessage + "', answer '" + oClientReader.ReadLine() + "'"
next
# STEP 5. Close everything: streams, then the connections, then the listener
oClient.Close()
oAccepted.Close()
oListener.Stop()
? nl + "STEP 5: closed"
# Real programs run the server and the clients in different programs (or different computers).
# Then the server loops: while true, accept a client, read, answer. Ring code runs on one thread, so a server that
# talks to many clients at once checks oListener.Pending() and polls the clients one after another.STEP 1: the server listens on 127.0.0.1, port is chosen: 1
STEP 2: the client is connected: 1
STEP 3: the server accepted the connection
STEP 4: three messages
sent 'hello', answer 'echo: HELLO'
sent 'how are you', answer 'echo: HOW ARE YOU'
sent 'bye', answer 'echo: BYE'
STEP 5: closedHow it works#
The server side#
new TcpListener(new IPAddress().Loopback, 0) prepares a listener on the loopback address (127.0.0.1, reachable only from this computer) and port 0, which means "any free port". Start(NULL) starts it, and LocalEndpoint.Port tells which port was chosen.
The client side#
new TcpClient() is the client; Connect([ :hostname = "127.0.0.1", :port = nPort ]) connects. The operating system accepts the connection at once, even before the program calls AcceptTcpClient; this is why client and server can live in one program, without threads.
Accepting#
oListener.AcceptTcpClient() returns the server's end of the connection. Each end has a stream (GetStream()): bytes go in on one side and come out on the other.
Readers and writers#
Raw bytes are awkward; a StreamReader and a StreamWriter on the stream read and write lines of text. AutoFlush = True sends every line at once instead of waiting for a full buffer. A reader's ReadLine() waits until a whole line arrived.
The conversation#
For each message: the client writes a line, the server reads it, the server writes an answer, the client reads it. Each side must read exactly what the other side wrote; if both sides wait to read, the program hangs (a deadlock).
Closing#
Close the connections, then stop the listener.
Real servers#
In a real system the server and the clients are different programs. A server loops: accept a client, talk, accept the next. Ring code runs on one thread, so a server that serves many clients at once checks oListener.Pending() and polls its clients in turn; for a web server use the ASP.NET WebServer (the tutorial HTTP), which handles the threading for you.
What you learned#
- an address and a port identify the other side,
- listener/accept on the server, connect on the client,
- streams, readers and writers,
- each read needs a matching write.
Exercises#
- Make the server answer
pongtopingandunknownto anything else. - Let the client send a number; the server answers its square.
- Try a port that nobody listens on and catch the error from
Connect. - Print the address the client sees:
oClient.Client.RemoteEndPoint.ToString().