Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   OOP (https://www.clubdelphi.com/foros/forumdisplay.php?f=5)
-   -   Sockets (https://www.clubdelphi.com/foros/showthread.php?t=68420)

jlsc 12-06-2010 11:47:25

Sockets
 
Hola a todos,

Tengo una aplicacion cliente servidor hecha con sockets, envio mensajes del servidor a los clientes, el servidor no siempre está conectado solo cuando abro sesion en windows 2003 y lo ejecuto, los clientes verifican si el servidor está conectado cada cierto tiempo y si el servidor se está ejecutando se conectan, esto lo hago con un timer que intenta cada cierto tiempo activar el Client Socket, si se conecta detengo el timer y ya no se activa hasta que el servidor se desconecta o alguien mata el proceso del servidor, es decir on disconnect y en error connect, en este momento es cuando vuelvo a activar el timer, funciona bien pero despues de que los clientes no se pueden conectar por un largo tiempo me sale varias instancias del siguiente error:



Alguna opinión de este error.

Muchas gracias de antemano.

Un Saludo

Jorge

rgstuamigo 12-06-2010 16:05:01

A primera mano te puedo de decir que quizas estas malversando memoria, es decir no estas liberando o quizas estas haciendo un mal uso de ella.
Por lo que comentas puede que el error vaya por los Timer que usas, en todo caso solo estoy especulando por que sin ver código no se te puede ayudar..;)
Saludos...:)

jlsc 14-06-2010 16:06:43

Socket Error
 
Hola compañero,

Este es el codigo:

Código Delphi [-]
unit UMensaCliente;
interface
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,  Dialogs,
  StdCtrls, ScktComp, Mask, DBCtrls, ExtCtrls, jpeg, IdBaseComponent, IdComponent, IdTCPConnection,
  IdSimpleServer, IdTCPServer, IdMappedPortTCP, IdTCPClient, Sockets, Menus, Gauges, Buttons,
  Grids, DirOutln, ComCtrls, Spin, ShellApi, Winsock, IdIPWatch, ImgList;
type
  TThePhoneHouseForm = class(TForm)
    ClientSocket1: TClientSocket;
    IdIPWatch1: TIdIPWatch;
    Image3: TImage;
    mMensaje: TMemo;
    StatusBar1: TStatusBar;
    Panel1: TPanel;
    MainMenu1: TMainMenu;
    Menu1: TMenuItem;
    Cerrar1: TMenuItem;
    Timer1: TTimer;
    procedure FormCreate(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure Button1Click(Sender: TObject);
    procedure ClientSocket1Connect(Sender: TObject;
      Socket: TCustomWinSocket);
    procedure ClientSocket1Error(Sender: TObject; Socket: TCustomWinSocket;
      ErrorEvent: TErrorEvent; var ErrorCode: Integer);
    procedure FormDestroy(Sender: TObject);
    procedure ClientSocket1Read(Sender: TObject; Socket: TCustomWinSocket);
    procedure ClientSocket1Disconnect(Sender: TObject;
      Socket: TCustomWinSocket);
    procedure Timer1Timer(Sender: TObject);
    procedure Cerrar1Click(Sender: TObject);
  private
    { Private declarations }
    IconData : TNotifyIconData;
    procedure WMQueryEndSession(var Msg: TWMQueryEndSession); message WM_QUERYENDSESSION;
    procedure WMSysCommand(var Msg: TWMSysCommand); message WM_SYSCOMMAND;
    procedure Espabila(var Msg : TMessage); message WM_USER+1 ;
  public
    { Public declarations }
  end;
var
  ThePhoneHouseForm: TThePhoneHouseForm;
  ControlaError:Integer;
  
implementation
uses Acerca;
{$R *.dfm}
function GetUserName : string;
var
  tamanoBuffer: Cardinal;
  bufferUsuario: array[0..MAX_PATH] of Char;
begin
  tamanoBuffer := SizeOf(bufferUsuario);
  Windows.GetUserName(bufferUsuario, tamanoBuffer);
  Result := bufferUsuario;
end;
procedure TThePhoneHouseForm.WMQueryEndSession(var Msg: TWMQueryEndSession);
begin
ClientSocket1.Active:=false;
Application.Terminate;
ExitWindowsEx(EWX_FORCE,0);
end;
function IPAddrToName(IPAddr: string): string;
var
  SockAddrIn: TSockAddrIn;
  HostEnt: PHostEnt;
  WSAData: TWSAData;
begin
  WSAStartup($101, WSAData);
  SockAddrIn.sin_addr.s_addr := inet_addr(PChar(IPAddr));
  HostEnt := gethostbyaddr(@SockAddrIn.sin_addr.S_addr, 4, AF_INET);
  if HostEnt <> nil then
    Result := StrPas(Hostent^.h_name)
  else
    Result := '';
end;
procedure TThePhoneHouseForm.FormCreate(Sender: TObject);
begin
ClientSocket1.Port:= 9923;
ClientSocket1.Host:='10.34.18.125';
ClientSocket1.Active:=true;
ControlaError:=1;
end;
procedure TThePhoneHouseForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
 ClientSocket1.Active:=False;
end;
procedure TThePhoneHouseForm.WMSysCommand(var Msg: TWMSysCommand);
 begin
   if (Msg.CmdType = SC_Close) then begin
     with IconData do
     begin
       cbSize := sizeof(IconData);
       Wnd := Handle;
       uID := 100;
       uFlags := NIF_MESSAGE + NIF_ICON + NIF_TIP;
       uCallbackMessage := WM_USER + 1;
       {Usamos de icono el mismo de la aplicacion}
       {We use the same icon as the application}
       hIcon := Application.Icon.Handle;
       {Como Hint del icono, el nombre de la aplicacion}
       {The name of te app for the hint of the icon}
       StrPCopy(szTip, Application.Title);
     end;
     {Ponemos el icono al lado del reloj}
     {Place the icon next to the clock}
     Shell_NotifyIcon(NIM_ADD, @IconData);
     {Ocultamos la Form...}
     {Hide the form...}
     Hide;
   end else DefaultHandler(Msg);
 end;
procedure TThePhoneHouseForm.Espabila(var Msg : TMessage);
 {Aqui se recibe la pulsacion sobre el icono}
 {Here we recieve the click on the icon}
 var
   p : TPoint;
 begin
   if Msg.lParam = WM_LBUTTONDOWN then begin
   ThePhoneHouseForm.Show;
   ShowWindow(Application.Handle, SW_HIDE);
   {Y nos cargamos el icono de la system tray}
   {Destroy the systray icon}
   Shell_NotifyIcon(NIM_DELETE, @IconData);
   IconData.Wnd:=0;
   end;
 end;
procedure TThePhoneHouseForm.Button1Click(Sender: TObject);
begin
if ClientSocket1.Active=true then
ClientSocket1.Socket.SendText(mMensaje.text);
end;
procedure TThePhoneHouseForm.ClientSocket1Connect(Sender: TObject;
  Socket: TCustomWinSocket);
var
bTemp:TBitmap;
begin
ClientSocket1.Socket.SendText(ClientSocket1.Socket.LocalHost+','+ClientSocket1.Socket.LocalAddress+'  ,'+GetUserName+','+''+','+'Conectado'+',');
Statusbar1.Panels[0].Text :='Conectado';
Statusbar1.Panels[1].Text :='';
Timer1.Enabled:=false;
ControlaError:=1;
end;
procedure TThePhoneHouseForm.ClientSocket1Error(Sender: TObject;
  Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
  var ErrorCode: Integer);
begin
ClientSocket1.Active:=false;
Statusbar1.Panels[1].Text :='Desconectado: Imposible conectar a ' + ClientSocket1.Host + '     ';
Statusbar1.Panels[0].Text :='';
ControlaError:=0;
ErrorCode := 0;
Timer1.Enabled:=true;
end;

procedure TThePhoneHouseForm.FormDestroy(Sender: TObject);
begin
 ClientSocket1.Active:=False;
end;
procedure TThePhoneHouseForm.ClientSocket1Read(Sender: TObject;
  Socket: TCustomWinSocket);
begin
ThePhoneHouseForm.Show;
ShowWindow(Application.Handle, SW_HIDE);
   {Y nos cargamos el icono de la system tray}
   {Destroy the systray icon}
Shell_NotifyIcon(NIM_DELETE, @IconData);
IconData.Wnd:=0;
mMensaje.Clear;
mMensaje.Lines.Add(ClientSocket1.Socket.ReceiveText+' '+ TimeToStr(now));
end;
procedure TThePhoneHouseForm.ClientSocket1Disconnect(Sender: TObject;
  Socket: TCustomWinSocket);
begin
if ((ClientSocket1.Active=false) and (ControlaError<>0 ))then
ClientSocket1.Socket.SendText(ClientSocket1.Socket.LocalHost+','+ClientSocket1.Socket.LocalAddress+'  ,'+GetUserName+','+''+'*'+'Desconectado'+',');
ClientSocket1.Active:=false;
Statusbar1.Panels[1].Text :='Desconectado: Imposible conectar a ' + ClientSocket1.Host + '     ';
Statusbar1.Panels[0].Text :='';
Timer1.Enabled:=true;
ControlaError:=1;
end;
procedure TThePhoneHouseForm.Timer1Timer(Sender: TObject);
begin
if (ClientSocket1.Active=false) then
  ClientSocket1.Active:=True
end;
procedure TThePhoneHouseForm.Cerrar1Click(Sender: TObject);
begin
Acercade.Show;
Acercade.Timer1.Enabled:=true;
end;
end.

rgstuamigo 14-06-2010 23:31:38

Bueno no he revisado demasiado tú código pero para ir al grano por que no tratas de poner algunos puntos de ruturas(Break point) en las instruciones que sospeches que son la causante del error.;). En otras palabras por que no debugeas(Debug) tu aplicacion.;).
Saludos...:)

jlsc 14-06-2010 23:59:09

Socket error
 
Es que el fallo no me lo da en tiempo de compilación y tampoco me lo da siempre, es cuando está sin conectarse durante 12 horas o más aproximadamente. He cambiado el puerto de conexion a uno más bajo y he aumentado el tiempo del timer, pero no sé si funcionará. Lo que me vendria bien es limpiar el buffer del socket cada cierto tiempo, sabes como podria hacerlo.

Gracias

un saludo


La franja horaria es GMT +2. Ahora son las 18:24:17.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi