quinta-feira, 3 de setembro de 2020

DICAS 3064 -WINDEV TUTORIAL 87 -Licao 7.7-10-09-2020 11hrs-The sockets




https://youtu.be/aI3pKb04i54



Bom Dia/Boa Tarde/Boa Noite

Esse Ao Vivo vai estrear as 11:00 do dia 10/09/2020 

DICAS 3064 -WINDEV TUTORIAL 87 -Licao 7.7-10-09-2020 11hrs-The sockets
Tutoriel WINDEV : Leçon 7.7. Programmation avancée - Les sockets

ASSUNTOS

EXPLICANDO SOCKETS
VISAO GEARL
APLICATIVO DE SERVIDOR
APLICATIVO DE CLITENTE
CRIANDO O SOCKET 
TROCANDO DADOS
FECHANDO SOCKE 
EXEMPLO PCSOFT 
   Unit examples
    using sockets
FAZERNDO PROJETO SOCKET ELE ESTARA NO REPOSITORIO WINDEV 
    SOCKET_AMARILDO
ORGANIZANDO O PROJETO COM TRADUCAO
ORGANIZANDO OS CODIGOS EM PROCEDURES
MOSTRANDO O PROGRAMA FUNCIONANDO
EXPLICANDO O CODIGO 

   
Video original da Franca

https://youtu.be/7aP_s3jv6Zs


Playlist Windev Tutorial Amarildo
Playlist windev Franca PcSoft
Amarildo
Windev
WxSolucoes
Matos Informatica
Repositorio Windev
Site forum Google 
Video sobre 3 Mil Videos Windev 
PlayList Pedrosao
Video sobre Alfaserver servidor 

DICAS 2979 - WINDEV TUTORIAL 2 - 1.2- CRIAR JANELA E INSERIR TEXTO E EXIBIR
DICAS 2980 - WINDEV TUTORIAL 3 - 2.1- VARIAVEIS PARTE 1
DICAS 2981 - WINDEV TUTORIAL 4 - 2.2- VARIAVEIS ESCOPO - PARTE 2
DICAS 2982 - WINDEV TUTORIAL 5 - 2.1- VARIAVEIS OPERADORES PARTE 3
DICAS 2983 - WINDEV TUTORIAL 6 - 2.1.D - VARIAVEIS STRINGS PARTE 4
DICAS 2984 - WINDEV TUTORIAL 7 - 2.1.E - VARIAVEIS ARRAYS PARTE 5
DICAS 2985 - WINDEV TUTORIAL 8 - 2.2.A - CONDICOES IF-SWITCH PARTE 1
DICAS 2986 - WINDEV TUTORIAL 9 - 2.2.B - CONDICOES PARTE 2
DICAS 2987 - WINDEV TUTORIAL 10 - 2.3.A - LOOP PARTE 1
DICAS 2988 - WINDEV TUTORIAL 11 - 2.3.B - LOOP EXEMPLOS PARTE 2
DICAS 2989 - WINDEV TUTORIAL 12 - Lesson 2.4. The procedures - PARTE 1
DICAS 2990 - WINDEV TUTORIAL 13 - Leçon 2.4.b. Procedures Parametros - PARTE 2
DICAS 2991 - WINDEV TUTORIAL 14 - PROCEDURES REFERENCIA - PARTE 3
DICAS 2992 - WINDEV TUTORIAL 15 - PROCEDURES OPCIONAIS OU OBRIGATORIAS - PARTE 4
DICAS 2993 - WINDEV TUTORIAL 16 - PROCEDURES EXEMPLOS - PARTE 5
DICAS 2994 - WINDEV TUTORIAL 17 - PERGUNTAS E RESPOSTA - PARTE 1
DICAS 2995 - WINDEV TUTORIAL 18 - PERGUNTAS E RESPOSTA - PARTE 2
DICAS 2996 - WINDEV TUTORIAL 19 - WINDEV E OS BANCOS DE DADOS
DICAS 2997 - WINDEV TUTORIAL 20 - PROJETO E ANALISE - CRIACAO
DICAS 2998 - WINDEV TUTORIAL 21 - PROJETO E ANALISE - ARQUIVOS DADOS CLIENTE - PARTE 2
DICAS 2999 - WINDEV TUTORIAL 22 - PROJETO E ANALISE - ARQUIVOS DADOS CRIACAO ARQUIVO PEDIDO - PARTE 3
DICAS 3000 - WINDEV TUTORIAL 23 - PROJETO E ANALISE - IMPORTANDO CVS-ARQUIVO TEXTO - PARTE 4
DICAS 3001 - WINDEV TUTORIAL 24 - PROJETO E ANALISE - IMPORTANDO ARQUIVO PRODUTO - PARTE 5
DICAS 3002 - WINDEV TUTORIAL 25 - PROJETO E ANALISE - LINK - PARTE 6
DICAS 3003 - WINDEV TUTORIAL 26 - RAD COMPLETO
DICAS 3004 - WINDEV TUTORIAL 27 - VISAO GERAL
DICAS 3005 - WINDEV TUTORIAL 28 - Adicionar e Modificar Janelas PRODUTOS - PARTE A
DICAS 3006 - WINDEV TUTORIAL 29 - Adicionar e Modificar Janelas PRODUTOS Formulario - PARTE B
DICAS 3007 - WINDEV TUTORIAL 30 - Adicionar e Modificar Janelas PRODUTOS ALINHAR CAMPOS - PARTE C


===================================================
PROCEDURE _00_DADOS_INICIAIS()

// CRIADO VARIAVEIS PARA NOS INFORMAR OS DADOS DOS COMPUTADORES E PORTAS
// CREATED VARIABLES TO INFORM US COMPUTER AND PORT DATA
// CRÉÉ DES VARIABLES POUR NOUS INFORMER LES DONNÉES DE L'ORDINATEUR ET DU PORT
// CREADO VARIABLES PARA INFORMAR NOSOTROS COMPUTADORAS Y DATOS PORTUARIOS

EDT_COMPUTADOR_SERVIDOR_A="COMPUTADOR_SERVIDOR_A"
EDT_COMPUTADOR_SERVIDOR_B="COMPUTADOR_SERVIDOR_B"
EDT_PORTA_SERVIDOR_A="9998"
EDT_PORTA_SERVIDOR_B="9999"
===================================================
PROCEDURE _01_CRIAR_SERVIDOR(sCOMPUTADOR_SERVIDOR is string,nPORTA_SERVIDOR is int)
// CRIADO VARIAVEL PARA MANDAR O RETORNO DO SERVIDOR
// CREATED VARIABLE TO SEND THE SERVER'S RETURN
// CRÉÉ UNE VARIABLE POUR ENVOYER LE RETOUR DU SERVEUR
// VARIABLE CREADA PARA ENVIAR EL RETORNO DEL SERVIDOR
sRETORNO_SERVIDOR is string=""
// RECEBE_NOME_COMPUTADOR = "COMPUTADORA"
// RECEBE_PORTA = 9998

// Crie um soquete localmente no computador para recuperar as mensagens de saída de nenhum outro usuário
// Create a socket locally on the computer in order to retrieve the outgoing messages no other user
// Créer une socket localement sur l'ordinateur afin de récupérer les messages sortants aucun autre utilisateur
// Cree un socket localmente en la computadora para recuperar los mensajes salientes que ningún otro usuario

// ComputerA é o identificador do nome do servidor.
// ComputerA is the identifier of the server name.
// ComputerA est l'identifiant du nom du serveur.
// ComputerA es el identificador del nombre del servidor.

// Este identificador permite que você recupere as mensagens enviadas por outros clientes.
// This identifier allows you to retrieve the messages sent by the other clients.
// Cet identifiant vous permet de récupérer les messages envoyés par les autres clients.
// Este identificador le permite recuperar los mensajes enviados por los otros clientes.

IF NOT SocketExist(sCOMPUTADOR_SERVIDOR) THEN
IF NOT SocketCreate(sCOMPUTADOR_SERVIDOR, nPORTA_SERVIDOR) THEN
sRETORNO_SERVIDOR="Erro ao criar o soquete"+ ErrorInfo(errMessage)
sRETORNO_SERVIDOR+=CR+"COMPUTADOR ["+sCOMPUTADOR_SERVIDOR
sRETORNO_SERVIDOR+=CR+"PORTA ["+nPORTA_SERVIDOR
ELSE
sRETORNO_SERVIDOR="OK"+CR+ ... 
"SERVIDOR [ "+sCOMPUTADOR_SERVIDOR+CR+ ...
"PORTA [ "+nPORTA_SERVIDOR+CR+ ...
"A partir de agora, você pode receber as mensagens enviadas do computador B"+ ... 
"Para enviar uma mensagem do computador B"
END
ELSE
sRETORNO_SERVIDOR="Este servidor já existe"
END

RESULT sRETORNO_SERVIDOR
===================================================
PROCEDURE _02_CONECTAR_COMPUTADOR(sCOMPUTADOR_CLIENTE is string,nPORTA_CLIENTE is int)
// CRIADO VARIAVEL PARA MANDAR O RETORNO DA CONEXAO
// CREATED VARIABLE TO SEND CONNECTION RETURN
// CRÉÉ UNE VARIABLE POUR ENVOYER UN RETOUR DE CONNEXION
// CREADO VARIABLE PARA ENVIAR CONEXIÓN RETORNO
sRETORNO_CONEXAO is string=""
// SocketConnect é usado para conectar a um servidor de socket.
// SocketConnect is used to connect to a socket server.
// SocketConnect est utilisé pour se connecter à un serveur socket.
// SocketConnect se utiliza para conectarse a un servidor de socket.

// "sCOMPUTADOR_CLIENTE" é o nome do identificador que será usado para enviar as mensagens ao servidor de soquete.
// "sCOMPUTADOR_CLIENTE" is the name of the identifier that will be used to send the messages to the socket server.
// "sCOMPUTADOR_CLIENTE" est le nom de l'identifiant qui sera utilisé pour envoyer les messages au serveur socket.
// "sCOMPUTADOR_CLIENTE" es el nombre del identificador que se utilizará para enviar los mensajes al servidor de socket.

// Para poder acessar o servidor, especifique um número de porta e o endereço IP do computador servidor.
// To be able to access the server, specify a port number and the IP address of the server computer.
// Para poder acessar o servidor, especifique um número de porta e o endereço IP do computador servidor.
// Para poder acceder al servidor, especifique un número de puerto y la dirección IP de la computadora del servidor.
IF NOT SocketExist(sCOMPUTADOR_CLIENTE) THEN
IF NOT SocketConnect(sCOMPUTADOR_CLIENTE, nPORTA_CLIENTE, EDT_AddressComputerB) THEN
sRETORNO_CONEXAO="Erro ao conectar ao endereço"+ErrorInfo(errMessage)
    ELSE
        sRETORNO_CONEXAO="OK"+CR
        sRETORNO_CONEXAO+="COMPUTADOR CLIENTE [ "+sCOMPUTADOR_CLIENTE+CR
sRETORNO_CONEXAO+="PORTA [ "+nPORTA_CLIENTE+CR
sRETORNO_CONEXAO+="ENDERECO [ "+EDT_AddressComputerB
END
ELSE
sRETORNO_CONEXAO="Voce ja esta conectado"
END
// MANDANDO O RETORNO DA CONEXAO
// SENDING THE CONNECTION RETURN
// ENVOI DU RETOUR DE CONNEXION
// ENVIANDO LA CONEXION DEVOLUCION
RESULT sRETORNO_CONEXAO

===================================================
PROCEDURE _04_RECEBE_MENSAGEM(COMPUTADOR_QUE_RECEBE_MENSAGEM)

// CRIADO VARIAVEL PARA RECEBER O RETORNO DA MENSAGEM
// CREATED VARIABLE TO RECEIVE THE MESSAGE RETURN
// CRÉÉ UNE VARIABLE POUR RECEVOIR LE RETOUR DE MESSAGE
// VARIABLE CREADA PARA RECIBIR EL MENSAJE DEVOLUCIÓN

sMENSAGEM_RETORNO is string=""

//  SocketRead que é usado para ler o soquete que foi criado anteriormente
// SocketRead that is used to read the socket that was created earlier
// SocketRead utilisé pour lire le socket créé précédemment
// SocketRead que se usa para leer el socket que se creó anteriormente

sMENSAGEM_RETORNO = SocketRead(COMPUTADOR_QUE_RECEBE_MENSAGEM, False, 2000)
IF sMENSAGEM_RETORNO <> "" THEN
sMENSAGEM_RETORNO+=" - "+"recebida do IP #"+SocketClientInfo(COMPUTADOR_QUE_RECEBE_MENSAGEM, SocketAddress)
ELSE
sMENSAGEM_RETORNO="NAO RECEBIDO NADA DO "+CR+COMPUTADOR_QUE_RECEBE_MENSAGEM
END

RESULT sMENSAGEM_RETORNO

===================================================
PROCEDURE _05_DESCONECTAR(sCOMPUTADOR_SERVIDOR is string)

// Fecha o servidor que foi criado no computador.
//Closes the server that was created on the computer.
// Ferme le serveur qui a été créé sur l'ordinateur.
// Cierra el servidor que se creó en la computadora.

IF SocketExist(sCOMPUTADOR_SERVIDOR) THEN
SocketClose(sCOMPUTADOR_SERVIDOR)
END

===================================================
// CLICK BTN_CREATE_a

// CHAMANDO A PROCEDURE CRIAR SERVIDOR , MANDANDO O COMPUTADOR E A PORTA E PEGANDO RETORNO
// CALLING PROCEDURE TO CREATE SERVER, SENDING COMPUTER AND DOOR AND TAKING RETURN
// PROCÉDURE D'APPEL POUR CRÉER UN SERVEUR, ENVOYER L'ORDINATEUR ET LA PORTE ET LE RETOUR
// PROCEDIMIENTO DE LLAMADA PARA CREAR SERVIDOR, ENVÍO DE COMPUTADORA Y PUERTA Y RETORNO

STC_MENSAGEM=_01_CRIAR_SERVIDOR(EDT_COMPUTADOR_SERVIDOR_A,Val(EDT_PORTA_SERVIDOR_A))

IF STC_MENSAGEM[[1 TO 2]]="OK" THEN
BTN_Disconnect_A..State = Active
BTN_Get_A..State = Active
END

===================================================
// BTN_CONNECT_a

// ESTAMOS CHAMANDO A PROCEDURE CONTECTAR COMPUTADOR , MANDANDO O NOME DO SERVIDOR E PORTA 
// WE ARE CALLING PROCEDURE TO CONNECT COMPUTER, SENDING THE SERVER'S NAME AND PORT
// NOUS APPELONS LA PROCÉDURE POUR CONNECTER L'ORDINATEUR, ENVOYANT LE NOM ET LE PORT DU SERVEUR
// LLAMAMOS A PROCEDIMIENTO PARA CONECTAR COMPUTADORA, ENVIANDO NOMBRE Y PUERTO DEL SERVIDOR

STC_MENSAGEM=_02_CONECTAR_COMPUTADOR("PARA"+EDT_COMPUTADOR_SERVIDOR_B,Val(EDT_PORTA_SERVIDOR_B))

IF STC_MENSAGEM[[1 TO 2]]="OK" THEN
BTN_Send_A..State = Active
BTN_Disconnect_A..State = Active
END
===================================================
// click btn_send_A

// CHAMANDO A PROCEDURE ENVIA MENSAGEM , MANDANDO O SERVIDOR E A MENSAGEM
// CALLING PROCEDURE SEND MESSAGE, SENDING SERVER AND MESSAGE
// PROCÉDURE D'APPEL ENVOYER UN MESSAGE, ENVOYER UN SERVEUR ET UN MESSAGE
// PROCEDIMIENTO DE LLAMADA ENVIAR MENSAJE, ENVIAR SERVIDOR Y MENSAJE

STC_MENSAGEM=_03_ENVIA_MENSAGEM("PARA"+EDT_COMPUTADOR_SERVIDOR_B,EDT_SentenceToSendToComputerB)
===================================================

// BTN_GET_A 

// ESTAMOS CHAMANDO A PROCEDURE RECEBE MENSAGEM, INFORMANDO O SERVIDOR E PEGANDO O RETORNO
// WE ARE CALLING PROCEDURE RECEIVES MESSAGE, INFORMING THE SERVER AND TAKING THE RETURN
// NOUS APPELONS PROCÉDURE REÇOIT UN MESSAGE, INFORMER LE SERVEUR ET PRENDRE LE RETOUR
// ESTAMOS LLAMANDO PROCEDIMIENTO RECIBE MENSAJE, INFORMANDO AL SERVIDOR Y TOMANDO LA DEVOLUCION

EDT_SentenceReceivedFromComputerB=_04_RECEBE_MENSAGEM(EDT_COMPUTADOR_SERVIDOR_A)
===================================================

// ESTAMOS CHAMANDO A PROCEDURE DESCONECTAR E INFORMANDO O SERVIDOR
// WE ARE CALLING TO PROCEDURE DISCONNECT AND INFORM THE SERVER
// NOUS APPELONS A PROCEDURE DE DECONNECTER ET D'INFORMER LE SERVEUR
// LLAMAMOS AL PROCEDIMIENTO DE DESCONECTAR E INFORMAR AL SERVIDOR

_05_DESCONECTAR(EDT_COMPUTADOR_SERVIDOR_A)


BTN_Get_A..State = Grayed
BTN_Disconnect_A..State = Grayed
BTN_Send_A..State = Grayed
EDT_SentenceReceivedFromComputerB = ""
EDT_SentenceToSendToComputerB = ""





































Lesson 7.7. The sockets
This lesson will teach you the following concepts
  • Overview.
  • Server application.
  • Client application.
Lesson duration

Estimated time: 20 mn
Previous LessonTable of contentsNext Lesson
Overview
WINDEV proposes several functions used to perform an advanced management of sockets.
A socket is a communication resource used by the applications to communicate between computers regardless of the network type.
This communication mode is used to establish a communication between two applications found on different computers (connected by Internet or on the same local network) or on the same computer.
A WINDEV application can manage the sockets according to different modes:
  • Client WINDEV application: the application connects to any server and it exchanges data via a socket.
  • WINDEV, WEBDEV or WINDEV Mobile "Server" application: the WINDEV, WEBDEV or WINDEV Mobile application is a server, exchanging information by sockets with several client computers. The threads must be used to manage several simultaneous connections.

Example

WINDEV is supplied with a training example allowing you to understand the use of sockets: "WD Using sockets". This example is accessible from the WINDEV home page (Ctrl + <).
Server application: for a simplified server
WINDEV gives you the ability to create a simplified socket server. This server allows you to communicate with a single client computer at a time. This type of application is very useful when two remote applications must communicate.
The steps for creating a simplified server are as follows:
  1. Creating the socket.
  2. Exchanging data.
  3. Closing the socket.

Creating the socket

To create the socket, the server is using SocketCreate. A socket is associated with a specific port. For a simplified use of socket by programming on the server, specify the socket name.
The client computer will connect to this socket in order to exchange data. The connection between the two computers will be actually established during the first exchange of data between the two computers (which means when the server reads information for the first time).
The connection is established during the first successful attempt of SocketRead on the server.

Exchanging data

When two computers are using the same socket, a communication stream is established between these two computers. These two computers can read and write character strings on the socket.
Remark: To avoid locking the applications, the management of incoming messages is often performed by a specific thread.
To read and write on the socket, the WINDEV server application must use SocketRead and SocketWrite.
Caution: To perform a read operation, a write operation must have been done beforehand. For example:
  1. The client computer writes into the socket: it sends a request to the server.
  2. The server performs a read operation on the socket in a thread. As soon as a message is received, the message is processed by the server.
  3. If a response to the message is required, the server identifies the client computer (SocketClientInfo) and sends a response to it.

Closing the socket

To end the communication, the server can close the socket with SocketClose.
Remark: the socket can also be closed by the client computer.
Client Application
A client application of a socket server connects to a standard server in order to exchange information via socket.
Example: A client WINDEV application can connect to a standard news server on Internet.
The steps for creating a client application are as follows:
  1. Connecting to the server.
  2. Exchanging data.
  3. Ending the communication.

Connecting to the server

To connect to a server socket, all you have to do is use SocketConnect. This function is used to perform a request for connecting to the server.
The socket is identified by its port and by its address.

Exchanging data

When two computers are using the same socket, a communication stream is established between these two computers. These two computers can read and write character strings on the socket.
Remark: To avoid locking the applications, the management of incoming messages is often performed by a specific thread.
To read and write on the socket, the WINDEV client application must use SocketRead and SocketWrite.

Ending the communication

To end the communication, all you have to do is close the socket from the client computer with SocketClose.
Remark: you also have the ability to end the communication from the server.
Practical example
The programming of sockets will be presented via the unit example named "Using sockets".

Test of example

  • Open the unit example named "Using sockets".
  • Run the test of "WIN_Socket" window. A message will be sent from computer B to computer A. Computer A is the Server application and computer B is the Client application.
    1. On computer A, click the "Create" button to create the socket.
    2. Computer B can connect to the socket created by computer A. All you have to do is click the "Connect" button (in Computer B section).
    3. Computer B sends a message to computer A:
      • Type message to send in the "Sentence to send to computer A" area.
      • Click the "Send" button found in the "Computer B" area.
    4. To retrieve the message on computer A, click the "Get" button found in the "Computer A" area.
    5. Click the "Disonnect" buttons to disconnect the two computers.
  • Stop the window test to go back to the editor.

Studying the code used

  • Let's study the code of the different buttons that have been used.
  • First of all, we are going to study the processes performed by the socket server (computer A).
    1. Display the code of "Create" button found in the "Computer A" area:
      • Select the "Create" button.
      • Press F2 to display the events.
    2. In the "Click" event, you will see SocketCreate, which is used to create the socket. Close the code editor.
    3. Display the code of "Get" button found in the "Computer A" area:
      • Select the "Get" button.
      • Press F2 to display the events.
    4. The following code is used in the "Click" event:
      EDT_SentenceReceivedFromComputerB = SocketRead("ComputerA"False2000)
      IF EDT_SentenceReceivedFromComputerB <> "" THEN
      Info("Message received from IP address # "+...
      SocketClientInfo("ComputerA"SocketAddress))
      END
      You will notice the presence of SocketRead that is used to read the socket that was created beforehand. The message read is immediately displayed in the "EDT_SentenceReceivedFromComputerB" control. Close the code editor.
  • Let's study the processes performed by the client (computer B).
    1. Display the code of "Connect" button found in the "Computer B" area:
      • Select the "Connect" button.
      • Press F2 to display the events.
    2. In the "Click" process, you will see SocketConnect, which is used to connect to the socket created by computer A. Close the code editor.
    3. Display the code of "Send" button found in the "Computer B" area:
      • Select the "Send" button.
      • Press F2 to display the events.
    4. The following code is used in the "Click" event:
      IF NOT SocketWrite("ForComputerA", ...
      EDT_SentenceToSendToComputerA) THEN
      Error(ErrorInfo(errMessage))
      RETURN
      END
      You will notice the presence of SocketWrite that is used to send a message onto the socket to which computer B is connected. Close the code editor.
Remark: In this lesson, we have seen a "simple" communication between a server and a client computer: the client sends messages and the server processes the messages. You have the ability to create more complex applications.
You have the ability to establish a communication between two applications, both client and server. In this case, the management of threads becomes very important to manage the send operations and the responses.




Nenhum comentário:

Postar um comentário

Teste

Teste
teste