Web Sockets
CapeSoft Logo

CapeSoft NetTalk
WebSockets

Download Latest Version
Installed Version Latest Version

NetTalk WebSockets

Desktop WebSockets are available in NetTalk Desktop, NetTalk Server and NetTalk Apps. Applies to Desktop (ABC or Clarion) apps.

Server WebSockets are available in NetTalk Server and NetTalk Apps.  Applies to NetTalk Web Servers.

Introduction

The web makes use of a request / response approach to communication between the server and the client. The client (usually a browser) makes a request to the server, and gets a response. The connection between the client and the server is then closed (either immediately or after a short period of time.)

Because of this architecture the server can efficiently deal with large numbers of users. Very few, if any, server side resources are consumed, even for very large numbers of users.

Unfortunately this also means the server cannot "push" data to the client. If something on the server side changes then there's no way to push that update to the client, because there is no connection to the client.

For this reason it would be advantageous in some cases to have an open connection to the server, one which stays open, over which the server could "push" updated information to the client. The "cost" of this approach is that an open connection is maintained between the server and the client, which naturally then uses up an available connection on the server side.

This technology was added to the web standards in late 2011 and rolled in browsers sometime after that. Today most browsers support WebSockets.

NetTalk 9 introduced limited web socket functionality for the Server side. NetTalk 10 expands on the server side, and also adds WebSocket support to the client-side.

 WebSocket client support is included in NetTalk Desktop. Server and Client support is included in NetTalk Server.

Requirements

WebSocket Server and Clients do NOT require Cryptonite in order to work.

The NetWebSocketClient class (general client web socket support) does NOT require jFiles.

The NetWebSocketClientNetWebServer class (WebSocket Client to NetTalk Web Server) and NetWebSocketServer class require jFiles.

Protocol

The WebSocket protocol is named ws:// for insecure servers and wss:// if the connection will take place over a TLS connection.

The protocol itself is a binary level protocol, that works on the same port as the HTTP or HTTPS server. Since it works over the same ports, client-side firewall configuration is not an issue. However some proxy servers may not recognize WebSocket traffic and so may prevent the connection from working. In most cases this is solved by using WebSocket traffic over a secure (TLS) connection rather than an insecure connection.

Apart from an initial handshake the connection does not make use of the HTTP protocol.

The WebSocket protocol defines support for PING and PONG messages. These allow the connection to stay open for long periods of time. NetTalk supports PING and PONG in both the server and client classes, you don't need to do anything for these to work.

Files of Interest

NetWebSocketClient.IncEquates for Web Socket classes. Declaration of NetWebSocketsBase and NetWebSocketClient classes.
NetWebSocketClient.ClwCode for NetWebSocketsBase and NetWebSocketClient classes.
NetWebSocketServer.IncClass declaration for NetWebSocketServer class.
NetWebSocketServer.ClwCode for the NetWebSocketServer class.

WebSocket Client

A WebSocket client object can be added to a window. This object allows you to communicate with any WebSocket server. Use of the object is fairly simple only a handful of methods are involved. The class to use is NetWebSocketClient.

Connecting


To connect to a server the connect method is used. This takes a single parameter, the URL to connect to. The URL does not need to contain the protocol (ws:// or wss://) - if this is omitted then an insecure connection (ws://) is assumed (unless the SSL property has been set to true.) For convenience if http:// or https:// are used then these are treated as ws:// or wss:// respectivly.

for example

net.start()
net.connect('ws://capesoft.com')


or

net.start()
net.connect('wss://capesoft.com')


or

net.start()
net.SSL = true
net.connect('capesoft.com')


Remember that a connection is asynchronous, so this will initiate a connection, however a connection has not yet been established.  When the connection is established then the OnOpen method will be called. (OnOpen is called again if the connection is lost, and reopened.)

Once the connection is open then you can send messages to the server using either the SendText or SendBinary methods.

If you are communicating with a NetTalk Web Server, which supports WebSockets, then a few more methods, which provide some higher-level functionality are also available.

Aside: While the protocol should be ws: or wss: the object is smart enough to also accept http: or https: - it translates these to ws: and wss: as required.

If a connection fails to open (because the server is not listening at the moment of open) and the AutoReconnect property is true (which is is by default) then the connection will automatically go into a reconnecting state and will continue to attempt to open (as per the reconnecting rules below) until the Close method is called.

Reconnecting

The WebSocket protocol supports PING and PONG messages to keep the connection alive, and to check to see if the connection is alive. Support for these messages is built-in, you do not need to do anything to support them.

If a connection to a server is unexpectedly lost (and the AutoReconnect property is true, which it is by default) then the client will automatically try and reconnect to the server. During this time the TryingToReconnect property is set to true. (TryingToReconnect is set to false once a connection to the server is made.)  The time between tries is determined by the PingInterval property. This is (by default) set to 27 seconds. Events trigger the check, and the slowest event (the timer) is set to 13.5 seconds. So the maximum period between connection retries is (by default) is 40.5 seconds.

When a connection is opened, or lost, or re-opened then the ConnectionStateChanged method is called. This allows you to embed code in your procedure that changes a visual cue, or some other effect, that lets the user know the state of the connection. The ConnectionStateChanged method takes a parameter called pState, a LONG value which is one of netState:Open, netState:Handshaking or netState:Closed.

Reconnecting only takes place if the connection is lost unexpectedly. If you close manually (by calling close or disconnect) then a reconnection is not attempted. Some servers will pass a message before closing indicating that reconnecting is not desired. In these cases you can set the AutoReconnect property to false.

If an open, or reconnection is successful then the OnOpen method is called.

Sending Messages

Messages can be set as either Text values, or Binary values. The server you are talking to will indicate which one is preferred. In most cases the server will default to accepting text messages.

To send a Text message use the SendText method. This takes a String, or a StringTheory object, as the parameter. The object contains the text to send.

To send a Binary message use the SendBinary method. This also takes either a String or a StringTheory object as the parameter.

Receiving Messages

When a complete message is received then the ProcessMessage method is called. This method takes two parameters, a Long for the Message Type and a StringTheory object containing the message.

The Message Type will be one of NetOpCode:TextFrame, NetOpCode:BinaryFrame or NetOpCode:ConnectionClose.

You can process the message inside the method, doing whatever it is you need to do.

Disconnect

To disconnect from the server call the Close method.

JSON

Messages can contain any text or binary information. What you send to the server, and what the server sends to you is completely arbitrary, and can be in any format that you both agree to.

Most servers will use JSON when moving text messages to and from a client. These can be easily constructed, and parsed by both ends, so makes for a very convenient mechanism. While JSON is a common format for formatting text messages, any other formatting of text messages is possible.

WebSocket Client to NetTalk Web Servers

The NetWebSocketClient class described above is suitable for use against any server which supports the ws protocol. However each server will support different commands and responses. The developer will need to format packets to send, and also embed code in the  ProcessMessage method to manage that protocol.

NetWebSocketClientNetWebServer Class

NetTalk Web Servers support a simple text protocol for some common functionality. The NetWebSocketClientNetWebServer class is derived from the regular NetWebSocketClient class, but adds a few more methods to more easily make use of this server side functionality. This class is only useful when talking to NetTalk Web Servers. For other servers use the NetWebSocketClient class.

Of course the underlying SendText and SendBinary methods still exist in the NetWebSocketClientNetWebServer class so you can still use this class to further extend the functionality of your server/client combination.

The NetTalk Server allows you to easily watch server values and channels. If you register as a client then anytime those values change you will be notified.

Host Value

A Host Value is a variable on the server that is global to all users.

The program can watch this variable, in which case if it is changed by the server, or by another user, the new value will be sent to the program. If you have assigned a client-side variable when doing the watch then any changes on the server side will reflect on the client side (with no embed code required.)

The program can also set this variable. Once set the server will send it to any other program that is watching the variable.

For example;

WebPerformance          Group,pre(wp)
NumberOfRequests          Long
NumberOfSpiderRequests    Long
                        End

net.WatchHostValue('WebPerformance',WebPerformance) 

In this example two server-side Host variables (wp:NumberOfRequests and wp:NumberOfSpiderRequests) will be monitored. If the server side value changes then the client side value, in the group, will also change. A change will also trigger a notification to the ReceiveHostValue method where custom embed code can be added.

The second parameter to WatchHostValue is optional. If it is omitted then only a notification will be sent to the ReceiveHostValue method. 

Aside: In order for a Host Value on the server to change, someone has to change it. It can be changed by a client, or it can be changed by the server itself. In the above example, where clients are monitoring server performance, it would need code in the server to update these host values. However if two clients were connected to the same server, they could update the host values themselves, and all the other clients monitoring these values would also change. In this case no server code would be involved.

Channel

A Channel is similar to a Host value except that it allows for more limited scoping. Where a host variable is shared across all users, a channel can be shared among just some users. This is done by giving the Channel a Group name. Users using the same Group will see values from other users using the same Group.








WebSocket Server

Server WebSockets are available in NetTalk Server

Log

Sockets appear in the server log with the prefix WS.




Class Reference

NetWebSocketBase

The NetWebSocketBase class contains methods and properties only used by the NetWebSocketServer and NetWebSocketClient classes.

NetWebSocketClient

Included in NetTalk Desktop.

For an introduction to this class see WebSocket Client.

Derivation

  • NetWebSocketClient ( NetWebSocketClient.Inc / NetWebSocketClient.Clw )

Properties

PropertyDescription
AutoReconnect
(Long)
If this is true (the default state) then unexpected disconnections will trigger automatic reconnection attempts at intervals specified by PingInterval.
Connected
(Long)
This is true if a connection to the server is currently thought to be open.
Host
(String 255)
The host name of the server which is either open, or attempting to open.
LastOpenDate
(Long)
The date when information was either last sent, or last received, from the server. Clarion standard LONG format.
LastOpenTime
(Long)
The time when information was either last sent, or last received, from the server. Clarion standard LONG format.
PingInterval
(Long)
The amount of time, in hundredths of a second, of silence between the server and the client before a PING packet is sent to the server. If the server is not connected, then this indicates the time between connection reattempts.
Port
(Long)
The port number of the server which is either open or attempting to open.
SSLSet to true if the connection is secured using TLS.
TryingToReconnect
(Long)
This is set to true if the connection to the server has been unexpectedly lost, and not yet regained, and the AutoReconnect property is true.
CustomHeader
String (4096)
A string that allows you to add custom headers to the Upgrade Request to the server.

Methods

MethodDescription
CloseCloses a connection to the currently connected server.
ConnectConnects to a ws: or wss: server.
ConnectionStateChangedThe state of the connection to the server has changed.
DisconnectSee Close.
OnOpenA connection to the server has been established (or reestablished.)
ProcessMessageA message from the server has been received.
SendBinarySend a binary message to the server.
SendPingSend a Ping message to the server
SendTextSend a Text message to the server
StartReturn the object to it's default state.

Close

Close()

Description

Closes the currently open connection to the server. If the connection is already closed then it does nothing. If the client is in a TryingToReconnect state then it will cease trying to reconnect.

Return Value

The method returns nothing.

Example

net.close()

See Also

Connect

Connect

Connect (String p_Url)

Description

This method opens a connection to the server.

Parameters
ParameterDescription
p_UrlThe URL of the server to connect to. should include ;
1. The protocol (ws://, wss://). If omitted then ws:// is assumed. http:// and https:// can also be used (these are translated into ws:// and wss:// respectivly.)
2. The server address - either the IP address or the DNS name of the server.
3. The port number. If omitted then 80 is used for ws:// and 443 is used for wss://

Notes

This method is asynchronous. The connection is not open immediately after calling this method. Once the connection is open and ready for use then the ConnectionStateChanged method is also called with the state set to netState:Open.

Return Value

The method returns nothing.

Example

net.connect('wss://capesoft.com')

See Also

Close, ConnectionStateChanged

ConnectionStateChanged

ConnectionStateChanged (Long p_State)

Description

This method is called when the connection state to the server changes. Use this method to embed code to show the user the state of the current connection.

Parameters
ParameterDescription
p_StateOne of netState:ClosednetState:Handshaking, netState:Open

Return Value

The method returns nothing

See Also

Connect, Close

OnOpen

OnOpen()

Description

This method is called when a connection to the server is opened, or reestablished. This is a good place to add code if you need to initiate any kind of registration with the server.

Return Value

The method returns nothing

See Also

Connect, Close

ProcessMessage

ProcessMessage (Long p_MessageType, StringTheory p_Message)

Description

When data is received from the server then this method is called. This is where you would embed code to handle the incoming messages.

Parameters
ParameterDescription
p_MessageTypeOne of NetOpCode:Ping, NetOpCode:Pong, net:TextMessage, net:BinaryMessage. The Ping and Pong types can be ignored, these are handled internally. 
p_MessageA StringTheory object containing the message data.

Return Value

The method returns nothing.

See Also

SendBinary, SendText

SendBinary

SendBinary (StringTheory p_toSend)

Description

Sends the contents of a StringTheory object to the server. The decision of whether to send the data as SendBinary or SendText is based on the server you are connected to. The server specifies which approach they want for messages sent to them.

Parameters
ParameterDescription
p_ToSendThe data to send.

Return Value

The method returns nothing.

See Also

SendText

SendPing

SendPing(<StringTheory p_toSend>)

Description

Sends a Ping to the server. This has the effect of keeping the connection to the server alive (and detecting when it is no longer alive.)

Parameters
ParameterDescription
p_ToSendThe data to send to the server. This is not normally needed. If blank the value 'are you there?' is sent.

Notes

SendPing is called automatically if an event (any event) on the window occurs and more than the time specified in the PingInterval property has elapsed. The default ping interval is 27 seconds.

Because an event is needed to trigger a Ping the Timer event is automatically set for the window if it is either not set at all, or set to a value larger than half the PingInterval.

Return Value

The method returns nothing.

See Also



SendText

SendText (StringTheory p_toSend)

Description

Sends the contents of a StringTheory object to the server. The decision of whether to send the data as SendBinary or SendText is based on the server you are connected to. The server specifies which approach they want for messages sent to them.

Parameters
ParameterDescription
p_ToSendThe data to send.

Return Value

The method returns nothing.

See Also

SendBinary

Start

Start()

Description

Returns the object to a virgin state. Call this method if changing from one server to another.

Return Value

The method returns nothing.

See Also

Connect

NetWebSocketClientNetWebServer

Included in NetTalk Server and NetTalk Desktop

For an introduction to this class see WebSocket Client to NetTalk Web Servers.

Derivation

  • NetWebSocketClientNetWebServer( NetWebSocketClient.Inc / NetWebSocketClient.Clw )

Properties

PropertyDescription
WatchList
ClientWatchListQueueType
A queue of items that are being watched. This allows the list to be resent to the server automatically if the connection to the server is lost, and regained. Typically this queue is not access directly, but through one of the methods below.

MMethods

MethodDescription
AddChannelValueSend a new channel value to the server. It will then be passed on to any other clients that are watching the channel.
ReceiveChannelValueA channel value has changed on the server, and has been received at this client.
ReceiveHostValueA host value has changed on the server, and has been received by the client.
SetHostValueSet a host value on the server. It will then be passed on to any other clients that are watching that host value.
WatchChannelWatch a channel on the server. If any messages are sent to that channel then they will be sent on to this client.
WatchHostValueWatch a host value on the server. If that host value changes then it will be sent on to this client.

ReceiveHostValue

ReceiveHostValue (String p_HostValueName, String p_Value)

Description

This method is triggered when a new HostValue is sent to this program. If the p_Value parameter was set when WatchHostValue was called, then the new value has already been inserted into the local variable.

Parameters
ParameterDescription
p_HostValueNameThe name of the host variable.
p_Valuethe incoming value of the variable.

Return Value

The method returns nothing.

See Also

WatchHostValue, SetHostValue

SetHostValue

SetHostValue (String p_HostValueName, String p_Value)

Description

This method sends a new value to the server to be assigned to the specified host value.

Parameters
ParameterDescription
p_HostValueNamethe name of the host variable.
p_ValueThe value to write to the host variable.

Return Value

The method returns nothing.

See Also

WatchHostValue, ReceiveHostValue

WatchHostValue

WatchHostValue (String p_HostValueName, <*? p_Value>)
WatchHostValue (String p_HostValueName, *Group p_Group)

Description

Sends a message to the server asking to watch the specified host value. When the value changes on the server then the new value is sent to the client.

Parameters
ParameterDescription
p_HostValueNameThe name of the host value to watch.  If the value changes on the server then the new value will be sent to this client.
p_ValueA valiable in this program that must automatically be updated when a new value arrives from the server.
p_GroupIf the second parameter is a GROUP structure then this is the same as calling WatchHostValue for each component part of the group.

Return Value

The method returns nothing.

See Also

SetHostValue, ReceiveHostValue

NetWebSocketServer

Included in NetTalk Server and NetTalk Desktop

Derivation

Properties

PropertyDescription
  

Methods

MethodDescription
  
[End of this document]
Return to NetTalk Documentation Index