Ícone do site Aprenda Delphi

Crie um cliente e servidor Websocket robusto, escalonável e em tempo real

Build A Robust Scalable Real time Websocket Client Server

HTTP is one of, if not the most, widely used client-server protocols. It has been serving up our favorite web pages, blogs, and even this site for many years through its lifetime carried on the shoulders of the reliable TCP. But technology is evolving, and over time it has become clear there are some limitations with HTTP. The first thing is that HTTP is unidirectional. With HTTP, the client starts the request first and the server responds. So for every resource, the client is the one who polling for the resource. Added to that, HTTP expects that each interaction has a timeout before it’s assumed that the server is not responding. How can an IDE Software create a robust and scalable real-time Web Socket and Server? Let’s find out all the answers in this post.

Quais são as soluções para as limitações de HTTP?

Long-polling serves as a solution to the limitations of HTTP based technology. In this case, the client sends request with a long timeout. This allows the server lots of time to reply without the connection expiring due to inactivity or an inability to respond. This was a solution for up to a certain level, but this is very resource hogging. It’s because the server resources are reserved and dedicated to the client during the long polling.

Websockets são a melhor solução para limitações de HTTP?

Sim, Websockets são uma solução melhor para ajudar a mitigar algumas das limitações de tempo limite de HTTP. Websockets pode usar HTTP para inicializar a conexão e, usando a mesma conexão TCP, atualizar para um websocket. Com o Websockets, temos uma conexão bidirecional persistente que consome menos recursos do que as pesquisas longas. Tanto o servidor quanto o cliente podem enviar mensagens a qualquer momento. Hoje, a maioria dos navegadores da web oferece suporte ao protocolo Websocket. Além disso, a quinta versão do HTML (HTML5) inclui suporte para websockets. Portanto, em geral, o Websockets permite que você crie aplicativos cliente-servidor em tempo real.

Como faço para implementar aplicativos de websocket com Delphi ou C ++ builder?

IPWorks possui uma solução completa para implementação de servidor e cliente Websocket. Possui os seguintes componentes:

TipeCertMgr: Este componente é usado para armazenar certificados.

TipeWebSocketServer: Este é o componente do servidor que aceita solicitações de clientes de websocket.

TipeWebSocketClient: Este é o componente cliente que pode se conectar a um servidor websocket e enviar ou receber dados.

TipeWebSocketProxy: Este componente aceitará conexões Websocket para um servidor websocket e, em vez disso, redirecionará para outro servidor.

By using these components you can develop a complete Websocket client and server application. These components are native and doesn’t need any external libraries. Also the components are optimized and work efficiently. It’s very secure with the WebSocket Secure 256-bit encryption. These components are thread safe. As an added bonus they also have a good documentation to get started:

https://cdn.nsoftware.com/help/IWF/dlp/

Como faço para usar IPWorks WebSockets?

IPWorks fornece uma versão de teste gratuita de seu pacote de componentes WebSocket para Delphi e construtor C ++. Você pode avaliar esses componentes em seu aplicativo. Você pode adquirir os componentes deste link:

https://www.nsoftware.com/ipworks/ws/download.aspx

Você também pode usar o gerenciador de pacotes GetIt para pesquisar uma versão de avaliação do IPWorks:

https://getitnow.embarcadero.com

O instalador do componente IPWorks WebSockets vem com um aplicativo de demonstração que funciona imediatamente. Ele tem um pequeno servidor de eco Websocket e um aplicativo cliente para se conectar ao servidor websocket.

Aqui está um Delphi WebSocket Demonstração de servidor

Aqui está um Delphi WebSocket Demonstração do cliente

Como faço para criar um servidor WebSocket de demonstração no RAD Studio Delphi?

Para criar um servidor Websocket usando componentes IPWorks Websocket, basta arrastar e soltar um TipeWebSocketServer component to a form. You have to setup basic parameters like the port going to use and weather this is a SSL server or not. If it’s a SSL server, you have to add a TipeCertMgr component and assign certificate details there. Once you set the all mandatory parameters, you can set “Ouvindo” property to true and it will start the server and accept client requests through the port. Sever component has many events you can handle. Some of them are:

OnConnected: Aciona quando um novo cliente é conectado.

OnDataIn: Quando receber dados de um cliente

OnDisconnected: Aciona quando o cliente é desconectado.

OnError: Chamará com um ID de conexão, código de erro e uma descrição de erro para um erro.

Como faço para criar um cliente WebSocket de demonstração no RAD Studio Delphi?

Para criar um cliente Websocket, você pode usar o TipeWebSocketClient component. Just place the component on a form, set some mandatory parameters and you have the working client. Then you can call the procedure “Conectar (ws: // SERVIDOR: PORTA)” to connect to the server. Once your work is done, you can disconnect from the server by calling “Disconnect” procedure. The client also have similar event like the server.

OnConnected: Dispara quando conectado ao servidor.

OnDataIn: Ao receber dados do servidor.

OnDisconnected: Desconectado do servidor.

OnError: Isso irá chamar com um código de erro e uma descrição do erro para um erro.

IPWorks WebSockets é uma das melhores soluções para o desenvolvimento de aplicativos de servidor de cliente Websocket robustos, avançados, mas amigáveis ao desenvolvedor.

Sair da versão mobile