Ver Mensaje Individual
  #2  
Antiguo 10-03-2007
Avatar de seoane
[seoane] seoane is offline
Miembro Premium
 
Registrado: feb 2004
Ubicación: A Coruña, España
Posts: 3.717
Reputación: 24
seoane Va por buen camino
Ahora uno un poco mas complicado, aunque prometo buscar alguno mas sencillo

Pues bien, el siguiente código sirve para montar un servidor de números aleatorios. Cuando se ejecuta la función "Aleator" el programa se pone a escuchar por el puerto 1978, y cuando alguien se conecta a el, comienza a enviarle números aleatorios a intervalos de 100 milisegundos.

Código Delphi [-]
uses
  // Winsock tiene que estar en las uses
  Windows, SysUtils, Winsock;

// Cada conexion se ejecuta en un thread diferente
function ThreadProc(Socket: TSocket): Integer;
var
  Str: String;
begin
  Result:= 0;
  try
    // En este bucle se mandan los numeros
    repeat
      // Un retardo de 100 ms entre numero y numero
      Sleep(100);
      // Convertimos el numero a hexadecimal, para que quede bonito
      Str:= IntToHex(Random(MAXINT),8);
      // y lo mandamos hasta que nuestro cliente se desconecte 
    until send(Socket,PChar(Str)^,Length(Str)+1,0) = SOCKET_ERROR;
  finally
    // Cerramos la conexion
    Shutdown(Socket,SD_SEND);  // SD_SEND = 1;
    CloseSocket(Socket);
    // Terminamos el thread
    EndThread(0);
  end;
end;

// Este es el bucle principal
procedure Aleator;
var
  WSADATA: TWSADATA;
  ServerSocket: TSocket;
  LocalAddr: TSockaddr;
  ClientSocket: TSocket;
  RemoteAddr: TSockaddr;
  AddrSize: Integer;
  FDSet: TFDSet;
  TimeVal: TTimeVal;
  ThreadId: LongWord;
begin  
  Randomize;
  // Inicializamos Winsock
  if WSAStartup(MAKEWORD(1, 1), WSADATA) = 0 then
  try
    // Creamos el Socket del servidor
    ServerSocket := socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
    if ServerSocket <> INVALID_SOCKET then
    begin
      // Configuramos la ip y el puerto que vamos a usar
      with LocalAddr do
      begin
        sin_family := AF_INET;
        // Aqui colocamos el puerto a usar
        sin_port := htons(1978);
        // Aqui indicamos que usaremos cualquier ip de nuestro equipo
        sin_addr.s_addr := htonl(INADDR_ANY);
        // Si queremos limitarnos a una ip en concreto usaremos la siguiente linea
        // sin_addr.s_addr:= Inet_Addr('127.0.0.1');
      end;
      // Ponemos el Socket a la escucha ...
      if bind(ServerSocket, LocalAddr, sizeof(LocalAddr)) <> SOCKET_ERROR then
        if listen(ServerSocket, SOMAXCONN) <> SOCKET_ERROR then
        begin
          repeat
            TimeVal.tv_sec := 0;
            TimeVal.tv_usec := 500;
            FD_ZERO(FDSet);
            FD_SET(ServerSocket, FDSet);
            // Comprobamos el estado del socket
            if select(0, @FDSet, nil, nil, @TimeVal) > 0 then
            begin
              AddrSize := sizeof(RemoteAddr);
              // Aceptamos la nueva conexion y creamos un nuevo Thread
              ClientSocket := accept(ServerSocket, @RemoteAddr, @AddrSize);
              if ClientSocket <> INVALID_SOCKET then
                // Creamos un nuevo tread usando la API
                BeginThread(nil, 0, @ThreadProc, Pointer(ClientSocket),
                  0, ThreadID);
            end;
          until FALSE; // Aquí ponemos la condición que nos apetezca
        end;
    end;
  finally
    WSACleanup();
  end;
end;


Para probarlo solo tenemos que usar, por ejemplo, el telnet:
Código:
telnet 127.0.0.1 1978
Responder Con Cita