httpReadWebSocket()
The function reads web sockets.
Synopsis
int httpReadWebSocket(int idx, <string|blob|anytype>
&message)
;
Parameter
Parameter | Description |
---|---|
idx | The internal file descriptor of the opened TCP/IP connection in order to address the webSocket. |
message | The message that is read. See the example further below. |
Return value
The function httpReadWebSocket returns 0 on success, otherwise -1.
Error
Wrong or missing arguments.
Description
In the WebSocket protocol the client (browser) establishes a connection to the server. The server can send data to the browser without a request from the browser. Equally, the browser can send data to the server. This provides a significant advantage: the server sends updates and notifications to the client without waiting for a client request. Furthermore, the webSockets do not contain header data like HTTP and less bandwith is required for the communication. The TCP connection remains active after the data transmission and a bidirectional transmission of data is still possible.
httpReadWebSocket() is a waiting CTRL function (like e.g. dpGet). The function waits for a webSocket message from the client. Internally the HTTP server receives the messages from the client and saves them in a queue. The function httpReadWebSocket() reads the messages asynchronous from the queue. As long as the queue contains messages, the function returns 0.
If the socket is closed by the client, the function returns 1. Thus, the callback function can be closed since the socket was closed and messages are not returned anymore.
As long as a connection should be established, a thread must run. If the client closes the connection, the function httpReadWebSocket returns 1 the next time it is called.
If the server should close the connection, use the function httpCloseWebSocket() or close the thread via the callback function (with return).
Example
The following example activates the HTTP server, registers the function "websocket" as a web resource and reads and writes WebSocket messages via the functions httpWriteWebSocket and httpReadWebSocket.
#uses "CtrlHTTP"
void main()
{
httpServer(false,8080);
/* Activates an HTTP server, authentication is not used, the
port 8080 is used*/
httpConnect("websocket","/websocket","_websocket_");
/* The function registers the function "websocket" as web
resource */
}
dyn_mixed writeData;
void websocket(mapping map) /*Function definition*/
{
DebugN("WebSocket callback", map);
mixed any;
while ( httpReadWebSocket(map["idx"], any) == 0 )
{
DebugN("message received", any);
/*Reads and outputs the messages */
DebugN("sent message back", httpWriteWebSocket(map["idx"],
any));
/*Sends the messages back*/
any = "";
}
DebugN("webSocket closed");
}
Assignment
CTRL PlugIn
Availability
CTRL