This demo shows how build a Server Chat using TsgcWebSocketHTTPServer and WebSockets as communication protocol.
Every time a new peer sends a message, the server reads the message and broadcast the message to all connected clients.
Before start the server, you must configure it to set the listening port, if use a secure connection or not...
WSServer.HTTP2Options.Enabled := chkHTTP2.Checked;
if WSServer.HTTP2Options.Enabled then
begin
WSServer.SSLOptions.OpenSSL_Options.APIVersion := oslAPI_1_1;
WSServer.SSLOptions.Version := tls1_3;
end
else
begin
case cboOpenSSLAPI.ItemIndex of
0: WSServer.SSLOptions.OpenSSL_Options.APIVersion := oslAPI_1_0;
1: WSServer.SSLOptions.OpenSSL_Options.APIVersion := oslAPI_1_1;
end;
case cboTLSVersion.ItemIndex of
0: WSServer.SSLOptions.Version := tlsUndefined;
1: WSServer.SSLOptions.Version := tls1_0;
2: WSServer.SSLOptions.Version := tls1_1;
3: WSServer.SSLOptions.Version := tls1_2;
4: WSServer.SSLOptions.Version := tls1_3;
end;
end;
With WSServer.Bindings.Add do
begin
Port := StrToInt(txtDefaultPort.Text);
IP := txtHost.Text;
end;
procedure TfrmServerChat.WSServerMessage(Connection: TsgcWSConnection; const Text: string);
begin
WSServer.Broadcast(Text);
end;
WebSocket HTTP Server allows to handle WebSocket and HTTP Protocols on the same listening port, so a web-browser can request a web page to access your server. OnCommandGet is the event used to read the HTTP Request and send the HTTP Responses.
Use ARequestInfo parameter to read the HTTP Request and AResponseInfo to write the HTTP Response.
Basically, use the ARequestInfo.Document to read which document is requesting the client and send a response using the following properties: ResponseNo, ContentType and ContentText.
Example: a client request document '/jquery.js'
procedure TfrmServerChat.WSServerCommandGet(AContext: TIdContext; ARequestInfo:
TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
begin
if ARequestInfo.Document = '/jquery.js' then
begin
AResponseInfo.ContentText := pageJQuery.Content;
AResponseInfo.ContentType := 'text/javascript';
AResponseInfo.ResponseNo := 200;
end;
end;