Forum > Spanish

Enviar, recibir datos de un servidor

(1/2) > >>

mav:
Hola, que tal :
 Aquí tengo un servidor, el  más puro estilo MSDN, a este se conecta un cliente que
envía una cifra de 4 dígitos ej. (1234), he conseguido que se conecte el cliente, enviar los 4 dígitos
y recibir una respuesta...indeterminada :

--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---program Server; uses  windows,jwaws2tcpip,jwaWinSock2; const  DEFAULT_PORT    = '55555';  DEFAULT_BUFLEN = 255; var  recvbuf: array[0..DEFAULT_BUFLEN] of byte;//  i : Byte;  ret, recvbuflen  : integer;  SocketData       : TwsaData;  hints                : TAddrInfo;  Result,ptr         : PAddrInfo;  ListenSocket, ClientSocket : TSocket;  iResult, iSendResult          : Integer;  // 1º Iniciar  Winsock ---------------------------------------------------------------------------- begin  Initialize(SocketData);  ret := WSAStartup(WINSOCK_VERSION,SocketData);  if ret <> 0 then  begin    WriteLn('WSAStartup failed: ', ret);    ExitProcess(1);  end  else    WriteLn('WSAStartup Ok');   // 2º Crear un socket para el servidor-----------------------------------------------------------------   Initialize(hints);   hints.ai_family   := AF_INET;  hints.ai_socktype := SOCK_STREAM;  hints.ai_protocol := IPPROTO_TCP;  hints.ai_flags    := AI_PASSIVE;   Result := nil;   iResult := getaddrinfo(nil,DEFAULT_PORT,@hints, Result);  if iResult <> 0 then  begin    WriteLn('getaddrinfo failed : ', iResult);    WSACleanup;    ExitProcess(1);  end;  if Result = nil then  begin    WriteLn('MemAlloc Error');    Exit;  end;   ptr := Result;  ListenSocket := INVALID_SOCKET;   ListenSocket := socket(ptr^.ai_family,ptr^.ai_socktype,ptr^.ai_protocol);  if ListenSocket = INVALID_SOCKET then  begin    WriteLn('Error at socket(): ',WSAGetLastError);    freeaddrinfo(Result);    WSACleanup;    ExitProcess(1);  end;  // 3º Binding (enlazar) el socket -----------------------------------------------------------   iResult := bind(ListenSocket, ptr^.ai_addr, Integer(ptr^.ai_addrlen));  if iResult = SOCKET_ERROR then  begin    WriteLn('bind failed with error: ', WSAGetLastError);    freeaddrinfo(result);    closesocket(ListenSocket);    WSACleanup;    ExitProcess(1);  end;   // 4º Listening on a socket, escuchando...-----------------------------------------------------   if listen( ListenSocket, SOMAXCONN ) = SOCKET_ERROR then  begin    WriteLn('Listen failed with error: ', WSAGetLastError);    closesocket(ListenSocket);    WSACleanup;    ExitProcess(1);  end;   // 5º Aceptando una conexión-----------------------------------------------------------------   ClientSocket := INVALID_SOCKET;   ClientSocket := accept(ListenSocket, nil, nil);  if ClientSocket = INVALID_SOCKET then  begin    WriteLn('accept failed: ', WSAGetLastError);    closesocket(ListenSocket);    WSACleanup;    ExitProcess(1);  end;   // 6º Recibiendo y enviando datos............-----------------------------------------------------------   recvbuflen := DEFAULT_BUFLEN;   Initialize(recvbuf);  repeat    iResult := recv(ClientSocket, recvbuf, recvbuflen, 0);    if iResult > 0 then    begin      WriteLn('Bytes received: ', iResult);       //--WriteLn los bytes recibidos (el número de ellos está en iResult(4)), que van a ser una parte de recvbuf  ¿Como?        //--Operar con los bytes recibidos y enviarlos al cliente ¿Como?        iSendResult := send(ClientSocket, recvbuf, iResult, 0);      if iSendResult = SOCKET_ERROR then      begin        WriteLn('send failed: ', WSAGetLastError);        closesocket(ClientSocket);        WSACleanup();        Exit;      end;      WriteLn('Bytes sent: ', iSendResult);    end    else    if iResult = 0 then    begin      WriteLn('Connection closing...');    end    else    begin      WriteLn('recv failed: ', WSAGetLastError());      closesocket(ClientSocket);      WSACleanup();      Exit;    end;  until iResult <= 0;  // 7º Desconectando el servidor ---------------------------------------------------------------------------   iResult := shutdown(ClientSocket, SD_SEND);  if iResult = SOCKET_ERROR then  begin    WriteLn('shutdown failed with error: ', WSAGetLastError());    closesocket(ClientSocket);    WSACleanup();    Exit;  end;   // cleanup  closesocket(ClientSocket);  WSACleanup();end.  Las preguntas son:
  1- ¿Como podria escribir (WriteLn) los dígitos enviados por el cliente, para comprobar que está bien? y
  2- La respuesta que tengo que enviar es :
     (Los dos primeros dígitos XOR hora actual) + (Los tercero y cuarto digito Xor minuto actual)
    ...esto último casi lo tengo ya experimentando con DecodeTime un poco.
    ¿Como separo los dátos de dos en dos, para operar con ellos?


--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---Program project1;{ This program demonstrates the DecodeTime function } Uses sysutils;Var HH,MM,SS,MS, sumad, sumad2, sumad3: Word; Begin  DecodeTime(Time,HH,MM,SS,MS);  Writeln (format('The time is %d:%d:%d.%d',[hh,mm,ss,ms]));      //---------------------------------------  WriteLn(format('%d%d', [hh,mm])) ;      //                                          //  sumad := hh xor 12 ;                    //  WriteLn (format('%d', [sumad]));        //                                          //  sumad2 := mm xor 34 ;                   //  WriteLn (format('%d', [sumad2]));       //  //---------------------------------------    sumad3 := sumad+ sumad2;  WriteLn (format('%d', [sumad3]));  WriteLn(#13#10#13#10#13#10);   WriteLn (format('%d%d', [sumad,sumad2]));   ReadLn;End. 
Un saludo a todos y gracias.

Edson:

--- Quote from: mav on October 03, 2022, 10:11:15 pm ---Las preguntas son:
  1- ¿Como podria escribir (WriteLn) los dígitos enviados por el cliente, para comprobar que está bien? y
  2- La respuesta que tengo que enviar es :
     (Los dos primeros dígitos XOR hora actual) + (Los tercero y cuarto digito Xor minuto actual)
    ...esto último casi lo tengo ya experimentando con DecodeTime un poco.
    ¿Como separo los dátos de dos en dos, para operar con ellos?

--- End quote ---

1) No he usado jwaws2tcpip o jwaWinSock2 (¿Es Jedi?) pero se puede ver que lo que buscas debe estar en "recvbuf". Tal vez puedas encontrar algún ejemplo en la documentación o en páginas equivalentes. Si no encuentras en Lazarus, te puedes guiar de los ejemplos de Delphi.
2) Para separar una cadena, puedes usar la función copy() y tomar dos subcadenas de la cadena original. En tu caso las subcadenas serían '12' y '34'. Luego tienes que convertir esas cadenas a número si quieres aplicarles el XOR.

mav:
...jwaws2tcpip o jwaWinSock2 es Api de Windows, que uso porque en winsock no hay convertidas algunas estructuras y declaraciones del api
que si están en el jwa..El problema es, después de que al buffer (recvbuf: array[0..DEFAULT_BUFLEN] of byte;) le han llegado del servidor los 4 bytes.
¿Como los leo y posteriormente selecciono de dos en dos para operar con ellos :

--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---               i: char?, string?,                i:= Copy(recvbuf, 1,4);  //Evidentemente esto no se puede hacer pero sería lo que quiero               WriteLn(i);                       
 

mosquito:
Quizás podrías mandar desde el cliente en vez de '1234' algo como ':#1234'.
Después usar (PosEx(':#',vbuf)+1) y copiar los 4 bytes contiguos. Así podrías mandar datos con cualquier formato y poder encontrar tus 4 bytes siempre independientemente de donde se encuentren en el buffer.

USES
classes, sysutils, strutils;

Edson:

--- Quote from: mav on October 04, 2022, 02:12:45 am ---...jwaws2tcpip o jwaWinSock2 es Api de Windows, que uso porque en winsock no hay convertidas algunas estructuras y declaraciones del api
que si están en el jwa..El problema es, después de que al buffer (recvbuf: array[0..DEFAULT_BUFLEN] of byte;) le han llegado del servidor los 4 bytes.
¿Como los leo y posteriormente selecciono de dos en dos para operar con ellos :

--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---               i: char?, string?,                i:= Copy(recvbuf, 1,4);  //Evidentemente esto no se puede hacer pero sería lo que quiero               WriteLn(i);                     

--- End quote ---

No puedes aplicar copy() a un arreglo de bytes como es "recvbuf". Tal vez si fuera un arreglo de "char". Puedes probar, tal vez te acepte usar un arreglo de char en lugar de bytes.
Otra opción sería, si sabes que tienes los datos en un arreglo de bytes y sabes que te deben llegar 4 bytes (porque se deduce que deben ser 4 caracteres de acuerdo a lo que indicas), lo más facil sería hacer algo como:


--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---var parte1, parte2: string;...parte1 := chr(recvbuf[0]) + chr(recvbuf[1]) ;parte2 := chr(recvbuf[2]) + chr(recvbuf[3]) ; 
No es la forma más elegante, pero creo que se entiende la idea. Por si acaso no he probado el código, solo lo escribo de memoria.

Yo escribí una librería que trabaja con sockets, pero usa Synapse. Tal vez te pueda servir: https://github.com/t-edson/conSock/blob/0.5/conSockClient.pas



 

Navigation

[0] Message Index

[#] Next page

Go to full version