• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Real-Time Communication with WebSockets in TMS Sparkle

Sascha Оффлайн

Sascha

Заместитель Администратора
Команда форума
Администратор
Регистрация
9 Май 2015
Сообщения
1,486
Баллы
155
TMS Software Delphi  Components


What are WebSockets


In today's web-driven world, applications often require real-time communication between clients and servers. Whether it's a chat application, live notifications, or real-time data updates, the traditional HTTP request-response model can sometimes fall short. This is where

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

come into play.

WebSockets offer a way to open a persistent connection between a client and a server, allowing data to be exchanged in real-time without the need for repeated HTTP requests. Once established, a WebSocket connection remains open, enabling the server to push updates to the client instantly. This makes WebSockets ideal for applications that require low-latency communication and constant updates.

If you're familiar with applications like real-time stock trading platforms, multiplayer games, or even modern web-based chat services, chances are you've interacted with WebSocket technology without even realizing it. WebSockets provide the backbone for these kinds of interactive and dynamic experiences on the web.

WebSocket Support in TMS Sparkle


With the latest updates,

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

now includes support for WebSockets, allowing Delphi developers to build modern, real-time applications with ease. As part of the

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

suite, Sparkle provides a robust platform for handling WebSocket connections, making it simple to integrate real-time communication into your Delphi applications.

WebSocket support in Sparkle is currently available on HTTP.sys-based servers and is fully server-side. By defining specific WebSocket endpoints in your Sparkle server, you can upgrade incoming HTTP requests to WebSocket connections, enabling real-time communication with your clients.

How to Use WebSockets in TMS Sparkle

Adding WebSocket middleware


First thing you need to do is to add the WebSocket middleware to your Sparkle/XData server. The middleware will inspect the request and if it's a WebSocket request, it will provide an upgrader interface for you to upgrade the request to a WebSocket request.

Upgrading a Request to WebSocket


The first step in handling WebSocket communication is upgrading the incoming HTTP request to a WebSocket connection. In Sparkle, this is achieved using the

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

interface. Once the request is upgraded, you can manage the WebSocket connection using the

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

interface.

Here's a basic example of how to upgrade a request to WebSocket and start handling communication:

var
Upgrader: IWebSocketUpgrader;
WebSocket: IWebSocket;
begin
Upgrader := THttpServerContext.Current.Item<IWebSocketUpgrader>;
if Upgrader <> nil then
WebSocket := Upgrader.Upgrade;
end;


Once the connection is upgraded, you can use the

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

and

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

methods to handle messages or use the

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

and

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

methods for more granular control.

Sending and Receiving Messages


After upgrading the connection, you can start exchanging messages with the client. For instance, you might want to send a welcome message to the client as soon as the connection is established:

WebSocket.Send('Welcome to the WebSocket server!');


Similarly, you can receive messages from the client and handle them accordingly:

var
Msg: IWebSocketMessage;
begin
Msg := WebSocket.Receive;
if Msg.MessageType = TWebSocketMessageType.Text then
Log('Received: ' + Msg.Text);
end;


This allows for real-time communication between the client and server, with the ability to instantly react to user input or other events.

Managing WebSocket State


Sparkle also provides methods to manage the WebSocket connection's state, such as closing the connection when it's no longer needed:

WebSocket.Close(WebSocketStatusCodes.NormalClosure);

This ensures that your server handles connections efficiently and gracefully, freeing up resources when clients disconnect.

Example: Real-Time Echo Service


To give you a better idea of how to use WebSockets in Sparkle, here's a simple example of a WebSocket service that echoes messages back to the client:

[ServiceImplementation]
TWebSocketService = class(TInterfacedObject, IWebSocketService)
private
procedure Echo;
end;

procedure TWebSocketService.Echo;
var
Upgrader: IWebSocketUpgrader;
WebSocket: IWebSocket;
Msg: IWebSocketMessage;
begin
Upgrader := THttpServerContext.Current.Item<IWebSocketUpgrader>;
if Upgrader = nil then
begin
TXDataOperationContext.Current.Handler.SetStatusCode(400);
Exit;
end;

WebSocket := Upgrader.Upgrade;

while WebSocket.State = TWebSocketState.Open do
begin
Msg := WebSocket.Receive;
case Msg.MessageType of
TWebSocketMessageType.Text:
WebSocket.Send('Echo: ' + Msg.Text);
TWebSocketMessageType.Close:
WebSocket.SendClose(WebSocketStatusCodes.NormalClosure);
end;
end;
end;

initialization
RegisterServiceType(TWebSocketService);


This simple service upgrades the connection to WebSocket, listens for messages from the client, and echoes them back.

Sample application


If you install TMS Sparkle (registered or trial version), in folder "demos\websockets" (under the TMS Sparkle product folder) you will find a working demo, with a Sparkle WebSocket receiving and sending data to a web client application written in plain simple vanilla HTML/Javascript. Try it out!

Conclusion


WebSockets open up a whole new world of possibilities for real-time communication in your applications. With TMS Sparkle's WebSocket support, Delphi developers can now easily integrate this powerful technology into their projects. Whether you're building a chat application, a live notification system, or any other real-time service, WebSockets in Sparkle provide the tools you need.

To learn more about how to use WebSockets with TMS Sparkle, check out the

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

. If you're new to TMS BIZ products, you can also

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

and start exploring the full range of features available in Sparkle and other components.

Get started with real-time communication in your Delphi applications today with

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

!


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу