RingDotNetfor Ring

WebSockets

HTTP is a question and an answer. A WebSocket is a connection that stays open, so both sides can send a message whenever they like — the base of chats, live prices and games. This lesson runs a server and a client in one program and sends text, binary data and a long message in parts, and then closes the connection properly.

What you will learn#

The tutorials Sockets and UDP sent bytes over TCP and UDP. A WebSocket adds messages on top of TCP, and a browser can use it.

The program#

samples/UsingDotNet/tutorials/ch07_websockets.ring
# WebSockets - a connection that stays open: a client and a server in one program, text and binary messages, long messages in parts, closing
load "dotnet.ring"

using {
	"System"
	"System.Net"
	"System.Net.Sockets"
	"System.Net.WebSockets"
	"System.Threading"
}

oToken = ""                       # a token that cancels everything after 20 seconds, so that a mistake cannot hang the program

func main

	# HTTP is a question and an answer. A WEBSOCKET is a connection that stays open after the first HTTP request: both sides can send a
	# message whenever they like, which is what a chat, a live price list or a game needs. The first request asks to "upgrade" the
	# connection, and then the two sides send MESSAGES (text or binary) until one of them closes it.
	oSource = new CancellationTokenSource().@New([ :millisecondsDelay = 20000 ])
	oToken = oSource.Token

	# 1. The server: an HttpListener that accepts the upgrade. The port is a free one, found by asking the system for port 0.
	oProbe = new TcpListener(new IPAddress().Loopback,0)
	oProbe.Start(NULL)
	nPort = oProbe.LocalEndpoint.Port
	oProbe.Stop()
	oListener = new HttpListener()
	oListener.Prefixes.Add("http://localhost:" + nPort + "/")
	oListener.Start()
	? "1. the server listens"

	# 2. The client connects. Everything is done with tasks, and the program waits for each task where it must: connecting and accepting
	#    are two sides of one handshake, so both tasks are started first and then both are waited for.
	oClient = new ClientWebSocket()
	oConnect = oClient.ConnectAsync([ :uri = new Uri("ws://localhost:" + nPort + "/chat"), :cancellationToken = oToken ])
	oContextTask = oListener.GetContextAsync()
	oContextTask.Wait(NULL)
	oContext = oContextTask.Result
	? nl + "2. a request arrived for " + oContext.Request.Url.AbsolutePath + ", it is a WebSocket request: " + yesNo(oContext.Request.IsWebSocketRequest)
	oAccept = oContext.AcceptWebSocketAsync(dnNull())                  # (no sub protocol)
	oAccept.Wait(NULL)
	oConnect.Wait(NULL)
	oServer = oAccept.Result.WebSocket
	? "   client state: " + oClient.State + ", server state: " + oServer.State

	# 3. Text messages. The client sends, the server receives and answers, the client receives the answer.
	? nl + "3. text messages:"
	for cText in [ "hello", "how are you?" ]
		sendText(oClient,cText,True)
		cGot = receiveText(oServer)
		? "   the server received '" + cGot + "'"
		sendText(oServer,upper(cGot),False)
		? "   the client received '" + receiveText(oClient) + "'"
	next

	# 4. A binary message: all 256 byte values (a Ring text can hold any byte)
	cBytes = ""
	for i = 0 to 255
		cBytes += char(i)
	next
	send(oClient,cBytes,"Binary",True)
	aGot = receive(oServer,1024)
	? nl + "4. a binary message of " + len(cBytes) + " bytes: the server received " + len(aGot[1]) + " bytes, of type " + aGot[2] + ", the same: " + yesNo(aGot[1] = cBytes)

	# 5. A long message comes in PARTS. The receiver has a buffer of 8 bytes, so a message of 20 bytes needs three calls of Receive; the
	#    result says EndOfMessage when the message is complete.
	sendText(oClient,"0123456789ABCDEFGHIJ",True)
	? nl + "5. a message of 20 bytes, a buffer of 8 bytes:"
	cWhole = ""
	nParts = 0
	while True
		aPart = receive(oServer,8)
		cWhole += aPart[1]
		nParts++
		? "   part " + nParts + ": '" + aPart[1] + "', last part: " + yesNo(aPart[3])
		if aPart[3]
			exit
		ok
	end
	? "   the whole message: " + cWhole

	# 6. Closing. One side starts the close handshake (CloseOutput says "I send no more"), the other receives the close message and
	#    answers with its own, and then both are Closed.
	oClient.CloseOutputAsync("NormalClosure","bye",oToken).Wait(NULL)
	aClose = receive(oServer,64)
	? nl + "6. the server received a message of type " + aClose[2] + ", status " + oServer.CloseStatus + ", description '" + oServer.CloseStatusDescription + "'"
	oServer.CloseAsync("NormalClosure","bye too",oToken).Wait(NULL)
	receive(oClient,64)
	? "   client state: " + oClient.State + ", server state: " + oServer.State

	oListener.Stop()

# send a text or binary message in one piece: the text is turned into an ArraySegment of bytes (the part of an array that is sent). The
# class ClientWebSocket has SendAsync with four values; the object that the server got is a WebSocket, where SendAsync has more forms and
# takes the values by name.
func send oSocket,cBytes,cType,lClient

	oSegment = new ArraySegment([ :typeArguments = ["System.Byte"], :array = cBytes ])
	if lClient
		oSocket.SendAsync(oSegment,cType,True,oToken).Wait(NULL)
	else
		oSocket.SendAsync([ :buffer = oSegment, :messageType = cType, :endOfMessage = True, :cancellationToken = oToken ]).Wait(NULL)
	ok

func sendText oSocket,cText,lClient

	send(oSocket,cText,"Text",lClient)

# Receive into a buffer of nSize bytes. The buffer is a byte buffer (dnBuffer): a .NET byte[] that Ring holds. The ArraySegment is made
# on that array, .NET fills it, and the received bytes are the first Count bytes of the buffer. The answer is [the bytes, the type,
# EndOfMessage].
func receive oSocket,nSize

	oBuffer = dnBuffer(nSize)
	oSegment = new ArraySegment([ :typeArguments = ["System.Byte"], :array = oBuffer ])
	oTask = oSocket.ReceiveAsync(oSegment,oToken)
	oTask.Wait(NULL)
	oResult = oTask.Result
	return [ dnBufferBytes(oBuffer,oResult.Count), "" + oResult.MessageType, oResult.EndOfMessage ]

func receiveText oSocket

	return receive(oSocket,1024)[1]

func yesNo lValue

	if lValue
		return "yes"
	ok
	return "no"
Output
1. the server listens

2. a request arrived for /chat, it is a WebSocket request: yes
   client state: Open, server state: Open

3. text messages:
   the server received 'hello'
   the client received 'HELLO'
   the server received 'how are you?'
   the client received 'HOW ARE YOU?'

4. a binary message of 256 bytes: the server received 256 bytes, of type Binary, the same: yes

5. a message of 20 bytes, a buffer of 8 bytes:
   part 1: '01234567', last part: no
   part 2: '89ABCDEF', last part: no
   part 3: 'GHIJ', last part: yes
   the whole message: 0123456789ABCDEFGHIJ

6. the server received a message of type Close, status NormalClosure, description 'bye'
   client state: Closed, server state: Closed
Note

This program uses a few generic functions (dnNew, getProp, dnBuffer, dnNull) where a class cannot be used. The lesson The generic functions explains them.

How it works#

The upgrade#

A WebSocket starts as a normal HTTP request with the headers Upgrade: websocket and Connection: Upgrade. The server answers 101 Switching Protocols, and from then on the connection is not HTTP any more: it carries messages in both directions until it is closed. In .NET the server side is an HttpListener: GetContextAsync() waits for a request, Request.IsWebSocketRequest says whether it asks for an upgrade, and AcceptWebSocketAsync does the upgrade and gives a WebSocket. (The WebServer of this package serves HTTP only; HttpListener is the .NET class for this job.) The program asks the system for a free port, so it cannot clash with another program.

One thread, two sides#

Server and client are both in the program, and Ring runs on one thread. The connecting and the accepting are two halves of one handshake, so the program starts both tasks first and then waits for both (Wait(NULL)). A cancellation token with a limit of 20 seconds makes every call fail with an error instead of waiting for ever if something is wrong.

Bytes and the bridge#

A message is a byte array. SendAsync takes an ArraySegment<byte>: a part of an array. A Ring text can hold any bytes, so dnNew with the .NET name of the closed type ArraySegment<byte> (the program shows how it is written) makes a segment, and the array inside it, from the bytes of the text. For receiving, .NET must write into an array that Ring can read afterwards, and a Ring text is copied when it goes in. So the program makes a byte buffer with dnBuffer(nSize): a .NET object that holds a live byte[]. The segment is made on that buffer, ReceiveAsync fills it, and dnBufferBytes(oBuffer, count) copies the first Count bytes into a Ring text. Ring strings are binary strings, so nothing is lost on the way (step 4 sends all 256 byte values).

Text and binary#

The message type is "Text" (the bytes are UTF-8 text) or "Binary" (anything). The server echoes each text in capital letters, so a round trip shows both directions. The result of ReceiveAsync has Count, MessageType and EndOfMessage.

Messages in parts#

A receiver has a buffer of a fixed size. A message that is bigger than the buffer comes in several parts, and EndOfMessage is false until the last one. The program reads in a loop and joins the parts: a message of 20 bytes with a buffer of 8 arrives as 8, 8 and 4. Real programs use a buffer of a few kilobytes and the same loop.

Closing#

Closing is a conversation too. The client calls CloseOutputAsync("NormalClosure", "bye", token), which says I send nothing more and does not wait. The server receives a message of type Close, and its CloseStatus and CloseStatusDescription are the status and the text of the client. The server answers with CloseAsync and the client receives that answer: now both states are Closed. A connection that is just dropped (the program ends, the cable is pulled) makes the other side raise an error on the next receive, which a program must expect.

Two forms of SendAsync#

The ClientWebSocket class has SendAsync with four plain values (segment, type, endOfMessage, token). The WebSocket that the server gets has more forms of the method, so there it is one method that takes a list of names. The function send knows which of the two it has.

Note

A server program that serves many clients needs one task for each connection, so that one slow client does not stop the others. Ring code runs on one thread, so such a server polls its connections in a loop (Wait with a short time limit) or uses the web server of the tutorial A web service with a database for the HTTP part.

What you learned#

Exercises#

  1. Make the server answer each message with its length.
  2. Send a message of 10,000 bytes with a buffer of 1,024 and count the parts.
  3. Let the client send a message after the server closed, and read the error.
  4. Send a JSON text (the tutorial JSON as a tree) and parse it on the other side.

Next#

HttpClient in depth

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.