i am very new to delphi and i have two projects written in delphi which must communicate - a client and a server. i have managed to get comms going for the connection and disconnection, but i can't get the client to send messages to the server at the click of a button - it appears that the messages do not make it to the server.
here is the client code:
unit my_client;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, IdAntiFreezeBase, IdAntiFreeze, IdTCPConnection,
IdTCPClient, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack,
IdBaseComponent, IdComponent;
type
TForm1 = class(TForm)
lstLog: TListBox;
Label1: TLabel;
txtData: TEdit;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
txtServer: TEdit;
txtPort: TEdit;
btnConnect: TButton;
btnSend: TButton;
btnDisconnect: TButton;
IdAntiFreeze1: TIdAntiFreeze;
Client: TIdTCPClient;
procedure btnConnectClick(Sender: TObject);
procedure btnSendClick(Sender: TObject);
procedure btnDisconnectClick(Sender: TObject);
private
ip: string;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btnConnectClick(Sender: TObject);
begin
Client.Host := txtServer.Text;
Client.Port := StrToInt(txtPort.Text);
ip := txtServer.Text + ':' + txtPort.Text;
lstLog.Items.Add('attempting to connect to ip [' + ip + ']');
with Client do
begin
try //try connecting
Connect;
lstLog.Items.Add('successfully connected to ip [' + ip + ']');
try //try getting data
lstLog.Items.Add('response: [' + Client.IOHandler.ReadLn() + ']');
BtnConnect.Enabled := False;
BtnSend.Enabled := True;
btnDisconnect.Enabled := True;
except
lstLog.Items.Add('cannot send data to ip [' + ip + ']');
Client.Disconnect();
end; //end try getting data
except
lstLog.Items.Add('cannot connect to ip [' + ip + ']');
end; //end try connecting
end; //end with
end; //end begin
procedure TForm1.btnSendClick(Sender: TObject);
begin
lstLog.Items.Add('sending data: [' + txtData.Text + ']...');
with Client do
begin
try
IOHandler.Write(txtData.Text);
lstLog.Items.Add('sent data: [' + txtData.Text + ']');
except
lstLog.Items.Add('failed to send data [' + ip + ']');
Client.Disconnect();
lstLog.Items.Add('Disconnect with ' + txtServer.Text + ' !');
BtnConnect.Enabled := True;
BtnSend.Enabled := False;
btnDisconnect.Enabled := False;
end;//end try
end;//end with
end;
procedure TForm1.btnDisconnectClick(Sender: TObject);
begin
Client.Disconnect();
lstLog.Items.Add('disconnected from ip [' + ip + ']');
BtnConnect.Enabled := True;
BtnSend.Enabled := False;
btnDisconnect.Enabled := False;
end;
end.
and here is my server code:
unit my_server;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, IdTCPConnection, IdTCPClient, IdBaseComponent,
IdComponent, IdCustomTCPServer, IdTCPServer, IdContext, IdThread, IdSync;
type
TfrmTCPServer = class(TForm)
edtPort: TEdit;
Label1: TLabel;
Label2: TLabel;
lbLog: TListBox;
btnStart: TButton;
btnStop: TButton;
IdTCPServer: TIdTCPServer;
procedure btnStartClick(Sender: TObject);
procedure btnStopClick(Sender: TObject);
procedure IdTCPServerConnect(AContext: TIdContext);
procedure IdTCPServerExecute(AContext: TIdContext);
procedure IdTCPServerDisconnect(AContext: TIdContext);
procedure IdTCPServerException(AContext: TIdContext;
AException: Exception);
private
{ Private declarations }
public
end;
var
frmTCPServer: TfrmTCPServer;
implementation
uses
StrUtils;
{$R *.dfm}
procedure TfrmTCPServer.btnStartClick(Sender: TObject);
begin
IdTCPServer.DefaultPort := StrToInt(EdtPort.Text);
IdTCPServer.Active := True;
BtnStart.Enabled := False; //don't let it be clicked again
BtnStop.Enabled := True; //let it be clicked again
lbLog.Items.Add('server started');
end;
procedure TfrmTCPServer.btnStopClick(Sender: TObject);
begin
if IdTCPServer.Active = true then
begin
IdTCPServer.Active := False;
BtnStart.Enabled := True; //let it be clicked now
BtnStop.Enabled := False; //don't let it be clicked again
lbLog.Items.Add('server stopped');
end
else
begin
lbLog.Items.Add('server already stopped');
end
end;
procedure TfrmTCPServer.IdTCPServerConnect(AContext: TIdContext);
begin
try
AContext.Connection.IOHandler.WriteLn('100: welcome to tcp test server');
lbLog.Items.Add('server received connection from [' + Acontext.Connection.Socket.Binding.PeerIP + ']');
except
lbLog.Items.Add('got here2');
end;
end;
procedure TfrmTCPServer.IdTCPServerExecute(AContext: TIdContext); //this is looped infinitely?
var
client_data: string; //strCommand
begin
with AContext.Connection do
begin
IOHandler.CheckForDataOnSource(10);
if not IOHandler.InputBufferIsEmpty then
begin
client_data := IOHandler.ReadLn();
IOHandler.WriteLn('received data [' + client_data + ']');
lbLog.Items.Add('received data [' + client_data + '] from ' + Socket.Binding.PeerIP);
end; //end if
end; //end with
end;
procedure TfrmTCPServer.IdTCPServerDisconnect(AContext: TIdContext);
begin
lbLog.Items.Add('client at ip [' + Acontext.Connection.Socket.Binding.PeerIP + '] has disconnected');
end;
procedure TfrmTCPServer.IdTCPServerException(AContext: TIdContext;
AException: Exception);
begin
lbLog.Items.Add('server exception: [' + AException.Message + ']');
end;
end.
the problem seems to lie in the IdTCPServerExecute procedure on the server. maybe i am not using it correctly, or maybe i need to set up some parameters before using this procedure?
Your server code is calling IOHandler.ReadLn(), which expects a (CR)LF after the text. Your client is calling IOHandler.Write(), which does not send a (CR)LF. The client needs to call IOHandler.WriteLn() instead.
Related
I have just started working with Threads use the onexecute event with Delphi 2009, indy IdTCPServer1. I wrote a very basic application for testing and am getting an access violation on exit. The application runs fine and does everything I want it to, but I think that I am leaving "Threads running" on exit. I have no experience with threads so any help would be appreciated.
Heres my code
unit FT_Communicator_pas;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ScktComp, IdContext, IdTCPServer,
INIFiles, ExtCtrls, ComCtrls, adscnnct,
DB, adsdata, adsfunc, adstable, Wwdatsrc, Grids, Wwdbigrd, Wwdbgrid,
IdBaseComponent, IdComponent, IdCustomTCPServer;
type
TfrmMain = class(TForm)
IdTCPServer1: TIdTCPServer;
PgMain: TPageControl;
TsMain: TTabSheet;
tsConfig: TTabSheet;
Label1: TLabel;
Label2: TLabel;
txtServer: TEdit;
txtPort: TEdit;
Panel1: TPanel;
Panel3: TPanel;
tsLog: TTabSheet;
mnolog: TMemo;
Button1: TButton;
Button3: TButton;
procedure IdTCPServer1Connect(AContext: TIdContext);
procedure IdTCPServer1Execute(AContext: TIdContext);
procedure Button3Click(Sender: TObject);
procedure IdTCPServer1Disconnect(AContext: TIdContext);
procedure Logit(const Logstr: String);
procedure FormShow(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
procedure TfrmMain.Button1Click(Sender: TObject);
begin
IdTCPServer1.Active:=FALSE;
application.Terminate;
end;
procedure TfrmMain.Button3Click(Sender: TObject);
begin
IdTCPServer1.Active:=true;
end;
procedure TfrmMain.FormShow(Sender: TObject);
begin
PgMain.ActivePage:=tsMain;
EnableMenuItem( GetSystemMenu( handle, False ),SC_CLOSE, MF_BYCOMMAND or MF_GRAYED );
end;
procedure TfrmMain.IdTCPServer1Connect(AContext: TIdContext);
begin
mnoLog.lines.Add ('Connected from: ' + AContext.Connection.Socket.Binding.PeerIP);
end;
procedure TfrmMain.IdTCPServer1Disconnect(AContext: TIdContext);
begin
mnoLog.lines.Add ('Disconnected from: ' + AContext.Connection.Socket.Binding.PeerIP);
end;
procedure TfrmMain.IdTCPServer1Execute(AContext: TIdContext);
var
myReadln,mySendln,sqlqry:string;
begin
sleep(10);
myReadln:=AContext.Connection.IOHandler.ReadLn();
mnolog.Lines.Add(AContext.Connection.Socket.Binding.PeerIP + '>' + myReadln );
mySendln:= AContext.Connection.Socket.Binding.PeerIP + ' Sent me ' + myReadln;
AContext.Connection.IOHandler.WriteLn(mySendln);
try
except
on E:Exception do
begin
logit('Error occured During execute function ' + #13#10 + e.message);
end;
end;
end;
procedure TfrmMain.logit(const logstr:String);
var
curdate,Curtime:string;
StrGUID:string;
begin
StrGUID:=FormatDateTime('YYYYMMDDHHnnsszzz', Now())+'_ ';
mnolog.lines.add(StrGUID +logstr );
end;
end.
Your TIdTCPServer event handlers contain unsafe code in them.
TIdTCPServer is a multithreaded component, its events are triggered in the context of worker threads. But you are directly accessing a VCL UI control (mnoLog) without synchronizing with the main UI thread. Bad things happen when you do not synchronize, as the VCL is not thread-safe. You must synchronize properly when accessing the UI from a worker thread.
It is also important to avoid performing a synchronous synchronization when deactivating TIdTCPServer from the main UI thread, as that will cause a deadlock. Use an asynchronous synchronization instead.
Try something more like the following:
procedure TfrmMain.IdTCPServer1Connect(AContext: TIdContext);
begin
Logit('Connected from: ' + AContext.Connection.Socket.Binding.PeerIP);
end;
procedure TfrmMain.IdTCPServer1Disconnect(AContext: TIdContext);
begin
Logit('Disconnected from: ' + AContext.Connection.Socket.Binding.PeerIP);
end;
procedure TfrmMain.IdTCPServer1Execute(AContext: TIdContext);
var
myReadln, mySendln, peerIP: string;
begin
myReadln := AContext.Connection.IOHandler.ReadLn();
peerIP := AContext.Connection.Socket.Binding.PeerIP;
Logit(peerIP + '>' + myReadln);
mySendln := peerIP + ' Sent me ' + myReadln;
AContext.Connection.IOHandler.WriteLn(mySendln);
end;
procedure TfrmMain.IdTCPServer1Exception(AContext: TIdContext; AException: Exception);
begin
if not (AException is EIdConnClosedGracefully) then
Logit('Error occured. ' + AException.Message);
end;
procedure TfrmMain.Logit(const Logstr: String);
var
Str: string;
begin
Str := Trim(Logstr);
TThread.Queue(nil,
procedure
begin
mnolog.Lines.Add(FormatDateTime('YYYYMMDDHHnnsszzz', Now()) + ': ' + Str);
end
);
end;
Good day sir/ma
i want to create a status bar with a rolling information like
Os version
current User Name
Date and time
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, ComCtrls;
type
TForm1 = class(TForm)
tmr2: TTimer;
stsbr: TStatusBar;
procedure tmr2Timer(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.tmr2Timer(Sender: TObject);
begin
if tmr2.Interval = 3000 then begin
stsbr.Panels[1].Text:= FormatDateTime('dddd' + ', ' + 'dd/mm/yyyy',date) + ', ' + TimeToStr(Time);
tmr2.Interval := 3001;
end else if tmr2.Interval = 3001 then begin
tmr2.Interval := 3002;
stsbr.Panels[1].Text:= 'PC Owner: '+GetUsersName+ ' - '+ GetLocalPCName;
end else if tmr2.Interval = 3002 then begin
tmr2.Interval := 3003;
stsbr.Panels[1].Text:= GetOSVersion;
end else if tmr2.Interval = 3003 then begin
tmr2.Interval := 3000;
stsbr.Panels[1].Text:= GetCPUName;
end;
procedure Form.FormCreate(Sender: TObject);
begin
tmr2Timer(Sender);
end;
end
.
that my full code
what i wanted to Achieve was a moving Information on a status bar
Please Help if u can
thanks..
You should not use Timer.Interval as lookout value to determine which data you should show in status bar. Use separate variable to do that. It will make your code cleaner.
unit Unit1;
interface
uses
Winapi.Windows, System.SysUtils, System.Classes, System.Win.Registry,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.ComCtrls, Vcl.ExtCtrls;
type
TForm1 = class(TForm)
tmr2: TTimer;
stsbr: TStatusBar;
procedure FormCreate(Sender: TObject);
procedure tmr2Timer(Sender: TObject);
private
status: integer;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
function GetUsersName: string;
var
Buf: array [0 .. MAX_PATH] of Char;
BufSize: longword;
begin
Buf[0] := #$00;
BufSize := MAX_PATH;
if Winapi.Windows.GetUserName(Buf, BufSize) then Result := Buf
else Result := '';
end;
function GetLocalPCName: string;
var
Buf: array [0 .. MAX_COMPUTERNAME_LENGTH] of Char;
BufSize: longword;
begin
Buf[0] := #$00;
BufSize := MAX_COMPUTERNAME_LENGTH;
if Winapi.Windows.GetComputerName(Buf, BufSize) then Result := Buf
else Result := '';
end;
function GetOSVersion: string;
begin
Result := TOSVersion.ToString;
end;
function GetCPUName: string;
var
Reg: TRegistry;
begin
Result := '';
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_LOCAL_MACHINE;
if Reg.OpenKeyReadOnly('\Hardware\Description\System\CentralProcessor\0') then
begin
Result := Reg.ReadString('ProcessorNameString');
Reg.CloseKey;
end;
finally
Reg.Free;
end;
end;
procedure TForm1.tmr2Timer(Sender: TObject);
begin
case status of
0 : stsbr.Panels[1].Text:= FormatDateTime('dddd' + ', ' + 'dd/mm/yyyy',date) + ', ' + TimeToStr(Time);
1 : stsbr.Panels[1].Text:= 'PC Owner: ' + GetUsersName + ' - ' + GetLocalPCName;
2 : stsbr.Panels[1].Text:= GetOSVersion;
else stsbr.Panels[1].Text:= GetCPUName;
end;
inc(status);
if status > 3 then status := 0;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
status := 0;
// this property can also be set through IDE form designer
tmr2.Enabled := true;
// show initial status data
tmr2Timer(Sender);
end;
end.
my server has a list of 4 TCP connected clients . if list full , next client must reject
//Server side
unit ServerUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, IdThreadMgr, IdThreadMgrDefault, IdAntiFreezeBase, IdAntiFreeze,
IdUDPBase, IdUDPServer, IdBaseComponent, IdComponent, IdTCPServer,
StdCtrls, ExtCtrls,IdSocketHandle, ComCtrls, IdUDPClient, Grids,
IdTCPConnection, IdTCPClient;
type
TForm1 = class(TForm)
Panel1: TPanel;
Label3: TLabel;
Edit3: TEdit;
Button1: TButton;
IdTCPServer1: TIdTCPServer;
IdUDPServer1: TIdUDPServer;
IdAntiFreeze1: TIdAntiFreeze;
IdThreadMgrDefault1: TIdThreadMgrDefault;
StatusBar1: TStatusBar;
GroupBox2: TGroupBox;
IncomingText: TMemo;
GroupBox1: TGroupBox;
Clients_StringGrid: TStringGrid;
IdTCPClient1: TIdTCPClient;
procedure Button1Click(Sender: TObject);
procedure IdUDPServer1UDPRead(Sender: TObject; AData: TStream;
ABinding: TIdSocketHandle);
procedure ADDTCPConn(AThread: TIdPeerThread;i:Integer);
procedure DeleteRow1(VGrid: TStringGrid; VRow: integer);
procedure InsertRow1(VGrid: TStringGrid; Str1:String; Str2:String; Str3:String);
Procedure Add_To_StringGrid(Grid:TStringGrid; Str1:String; Str2:String; Str3:String; i:Integer);
procedure FormCreate(Sender: TObject);
procedure IdTCPServer1Execute(AThread: TIdPeerThread);
procedure IdTCPServer1Connect(AThread: TIdPeerThread);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
RCount:Integer;
flag:Boolean;
IPList : TStringList;
IPList2 : TStringList;
fl: Boolean;
implementation
uses CommonUnit;
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
if not IdUDPServer1.Active then
begin
IdUDPServer1.DefaultPort:=1717;
IdUDPServer1.BroadcastEnabled:=True;
IdUDPServer1.Active:=True;
end;
if not IdTCPServer1.Active then
begin
IdTCPServer1.DefaultPort:=1717;
IdTCPServer1.Active:=True;
end;
end;
procedure TForm1.IdUDPServer1UDPRead(Sender: TObject; AData: TStream;
ABinding: TIdSocketHandle);
var
s : String;
ip : String;
dss : TStringStream;
begin
try
dss := TStringStream.Create('');
dss.CopyFrom(AData, AData.Size);
s := dss.DataString;
ip:=GetIPAddress();
IncomingText.Lines.Add('Client Say('+ABinding.PeerIP+'):'+s);
IncomingText.Lines.Add('------------');
ABinding.SendTo(ABinding.PeerIP, ABinding.PeerPort, ip[1], Length(ip));
dss.Free();
except
on E : Exception do
WriteLogFile(E.message);
end;
end;
procedure TForm1.ADDTCPConn(AThread: TIdPeerThread;i:Integer);
var
NewClientIP : String;
begin
NewClientIP := AThread.Connection.Socket.Binding.PeerIP;
//NewClientHostName := IPAddrToName(NewClientIP);
//Add_To_StringGrid(Clients_StringGrid,NewClientIP,'ggg','eee',i);
InsertRow1(Clients_StringGrid,NewClientIP,'ggg','eee');
IncomingText.Lines.Add(TimeToStr(Time)+' Connection from "' + 'ggg' + '" on ' + NewClientIP);
IncomingText.Lines.Add('------------');
StatusBar1.Panels.Items[0].Text := ' Status : TCP Connected';
flag:=true;
end;
Procedure TForm1.Add_To_StringGrid(Grid:TStringGrid; Str1:String; Str2:String; Str3:String;
i:Integer);
Begin
if i=-1 then
begin
if RCount <> 0 then
Grid.RowCount := Grid.RowCount + 1;
RCount:=RCount+1;
Grid.Cells[0,RCount] := Str1;
Grid.Cells[1,RCount] := Str2;
Grid.Cells[2,RCount] := Str3;
end
else
begin
Grid.Cells[0,i] := Str1;
Grid.Cells[1,i] := Str2;
Grid.Cells[2,i] := Str3;
end;
End;
procedure TForm1.InsertRow1(VGrid: TStringGrid; Str1:String; Str2:String; Str3:String);
begin
if RCount<>0 then
VGrid.RowCount:= VGrid.RowCount + 1;
VGrid.Cells[0, VGrid.RowCount - 1]:= Str1;
VGrid.Cells[1, VGrid.RowCount - 1]:= Str2;
VGrid.Cells[2, VGrid.RowCount - 1]:= Str3;
RCount:=RCount+1;
end;
procedure TForm1.DeleteRow1(VGrid: TStringGrid; VRow: integer);
var
I, J: Integer;
begin
if VGrid.RowCount = 2 then
begin
VGrid.Rows[1].CommaText:= '"","","","",""';
end
else
begin
for I:= VRow to VGrid.RowCount - 2 do
for J:=0 to VGrid.ColCount - 1 do
VGrid.Cells[J,I]:= VGrid.Cells[J, I + 1];
VGrid.RowCount:= VGrid.RowCount - 1;
end;
RCount:=RCount-1;
if RCount=0 then
VGrid.RowCount:= 2;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
RCount:=0;
Clients_StringGrid.Cells[0, 0]:= 'Client IP';
Clients_StringGrid.Cells[1, 0]:= 'Host Name';
Clients_StringGrid.Cells[2, 0]:= 'Versa';
end;
procedure TForm1.IdTCPServer1Execute(AThread: TIdPeerThread);
begin
if flag then
AThread.Connection.WriteLn('Reply')
else
AThread.Connection.WriteLn('Reject');
end;
procedure TForm1.IdTCPServer1Connect(AThread: TIdPeerThread);
var
j:Integer;
fl:Boolean;
IP:String;
IPList2 : TStringList;
Count:Integer;
i:Integer;
begin
try
Count:=StrToInt(Edit3.Text);
IP:= AThread.Connection.Socket.Binding.PeerIP;
if (Clients_StringGrid.Cols[0].IndexOf(IP) = -1) then
begin
if RCount < Count then
begin
if (Clients_StringGrid.Cols[0].IndexOf(IP) = -1) then
ADDTCPConn(AThread,-1)
else
begin
StatusBar1.Panels.Items[0].Text := ' Status : TCP Already Connected';
flag:=True;
end;
end
else
begin
IPList:=TStringList.Create;
IPList2:=TStringList.Create;
fl:=False;
IPList.Clear;
IPList2.Clear;
For i:=1 To Count Do
begin
IdTCPClient1.Host := Clients_StringGrid.Cells[0,i];
IdTCPClient1.Port := 1112;
if IdTCPClient1.connected then
IdTCPClient1.Disconnect;
try
IdTCPClient1.Connect();
IdTCPClient1.Disconnect;
IPList.Add(Clients_StringGrid.Cells[0,i]);
except
on E : Exception do
begin
IPList2.Add(Clients_StringGrid.Cells[0,i]);
fl:=True;
end;
end;
end;
IncomingText.Lines.Add('Num Act ip:'+IntToStr(IPList.Count));
For j:=1 To IPList2.Count Do
begin
IncomingText.Lines.Add('row Del'+IntToStr(Clients_StringGrid.Cols[0].IndexOf(IPList2[j-1])));
DeleteRow1(Clients_StringGrid,Clients_StringGrid.Cols[0].IndexOf(IPList2[j-1]));
end;
if fl then
begin
ADDTCPConn(AThread,-1);
flag:=True;
end
else
flag:=false;
IPList.Free;
IPList2.Free;
end;
end
else
begin
StatusBar1.Panels.Items[0].Text := ' Status : TCP Already Connected';
flag:=True;
end;
except
on E : Exception do
WriteLogFile(E.message);
end;
end;
end.
//Client Side
unit ClientUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, IdAntiFreezeBase, IdAntiFreeze,
IdTCPConnection, IdTCPClient, IdBaseComponent, IdComponent, IdUDPBase,
IdUDPClient, ComCtrls, IdUDPServer,IdSocketHandle,IdStack, IdTCPServer,
IdThreadMgr, IdThreadMgrDefault;
type
TForm2 = class(TForm)
Panel1: TPanel;
Label3: TLabel;
Edit3: TEdit;
Button1: TButton;
Button2: TButton;
Button3: TButton;
StatusBar1: TStatusBar;
GroupBox2: TGroupBox;
IncomingText: TMemo;
IdUDPClient1: TIdUDPClient;
IdTCPClient1: TIdTCPClient;
IdAntiFreeze1: TIdAntiFreeze;
IdTCPServer1: TIdTCPServer;
IdThreadMgrDefault1: TIdThreadMgrDefault;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure IdTCPServer1Execute(AThread: TIdPeerThread);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form2: TForm2;
ServerIP:String;
implementation
uses CommonUnit;
{$R *.dfm}
procedure TForm2.Button1Click(Sender: TObject);
begin
if not IdUDPClient1.Active then
begin
IdUDPClient1.Port:=1717;
IdUDPClient1.BroadcastEnabled:=True;
IdUDPClient1.Active:=True;
IdTCPServer1.Active:=False;
end;
Button1.Enabled:=False;
Button2.Enabled:=True;
end;
procedure TForm2.Button2Click(Sender: TObject);
var
StrIn : String;
StrOut : String;
begin
try
StrOut:='Request';
IdUDPClient1.Broadcast(StrOut, 1717);
StrIn := IdUDPClient1.ReceiveString(100);
if not (StrIn='') then
begin
Button3.Enabled:=True;
Button2.Enabled:=False;
IncomingText.Lines.Add('UDP Reply');
StatusBar1.Panels.Items[0].Text := 'Status : UDP Connected';
ServerIP := StrIn;
end
else
WriteLogFile('UDP Connection Failed');
except
on E : Exception do
WriteLogFile(E.Message);
end;
end;
procedure TForm2.Button3Click(Sender: TObject);
var
StrIn : String;
begin
try
if ServerIP<>'' then
begin
IdTCPClient1.Host := ServerIP ;
IdTCPClient1.Port := 1717 ;
IdTCPClient1.Connect;
StrIn:= IdTCPClient1.ReadLn();
//IdTCPClient1.Disconnect;
if StrIn<>'' then
begin
IncomingText.Lines.Add(StrIn);
if StrIn<>'Reply' then
StatusBar1.Panels.Items[0].Text :='Connected To TCPServer';
else
begin
Button3.Enabled:=False;
Button1.Enabled:=True;
end;
end
else
WriteLogFile('TCP Connection Failed');
end;
except
on E : Exception do
WriteLogFile(E.message);
end;
end;
procedure TForm2.IdTCPServer1Execute(AThread: TIdPeerThread);
begin
//check point
end;
end.
//when in event onconnect on server want to check clients in list , line IdTCPClient1.Connect() return error
1)Socket Error # 10022 Invalid argument.
2)Connection Closed Gracefully.
and never run onexcute on client side
why this hapened
hello i am just new to delphi 7 and i have written a app which manages my mdb database. i just want to put a search box wherein if i put in a keyword it will return results with the keyword on a specific row of the database.
example: on the row named first name i want to search the database with the john keyword then when i hit enter or search button the app will return results with all the data containing john on its first name
type
Tcollector = class(TForm)
Image1: TImage;
ADOConnection1: TADOConnection;
ADOTable1: TADOTable;
DataSource1: TDataSource;
DBGrid1: TDBGrid;
DBNavigator1: TDBNavigator;
procedure DataSource1DataChange(Sender: TObject; Field: TField);
private
{ Private declarations }
public
{ Public declarations }
end;
var
collector: Tcollector;
implementation
{$R *.dfm}
procedure Tcollector.DataSource1DataChange(Sender: TObject; Field: TField);
begin
end;
EDIT:
i have done this:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, DBGrids, DB, ADODB, StdCtrls;
type
TForm1 = class(TForm)
ComboBox1: TComboBox;
ADOConnection1: TADOConnection;
ADOQuery1: TADOQuery;
DataSource1: TDataSource;
DBGrid1: TDBGrid;
Button1: TButton;
Button2: TButton;
ADOQuery2: TADOQuery;
ADOQuery3: TADOQuery;
ADOQuery4: TADOQuery;
ADOQuery5: TADOQuery;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses Unit2;
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
ADOConnection1.GetTableNames(ComboBox1.Items);
end;
procedure TForm1.Button1Click(Sender: TObject);
var tblname : string;
begin
if ComboBox1.ItemIndex < 0 then Exit;
tblname := ComboBox1.Items[ComboBox1.ItemIndex];
with ADOQuery1 do begin
Close;
SQL.Text := 'SELECT * FROM ' + tblname;
Open;
end;
with ADOQuery2 do begin
Close;
SQL.Text := 'SELECT * FROM ' + tblname;
Open;
end;
with ADOQuery3 do begin
Close;
SQL.Text := 'SELECT * FROM ' + tblname;
Open;
end;
with ADOQuery4 do begin
Close;
SQL.Text := 'SELECT * FROM ' + tblname;
Open;
end;
with ADOQuery5 do begin
Close;
SQL.Text := 'SELECT * FROM ' + tblname;
Open;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
form2.show;
end;
end.
so far i can pull all the table data. what i want my program to do is to display data which i have typed on a tedit
btw sorry for my first post im still not familiar with the forum shortcuts and rules on posting. :D
TDataSet.Filter
or
TDataSet.OnFilterRecord
or use SQL directly.
got it just some minor problems but maybe i can figure it out
begin
ADOTable1.First;
if ADOTable1.Locate('Last',edit1.Text ,[]) then begin
Label1.Caption := ADOTable1.FieldByName('Last').AsString;
Label2.Caption := ADOTable1.FieldByName('First').AsString;
Label3.Caption := ADOTable1.FieldByName('address').AsString;
Next;
end else begin
Label1.Caption := '';
Label2.Caption := '';
Label3.Caption := '';
im new to delphi. and also almost new to programming world.
i was made some simple post software which using idhttp module.
but when execute it , it not correctly working.
this simple program is check for my account status.
if account login successfully it return some source code which include 'top.location ='
in source, and if login failed it return not included 'top.location ='
inside account.txt is follow first and third account was alived account
but only first account can check, after first account other account can't check
i have no idea what wrong with it
ph896011 pk1089
fsadfasdf dddddss
ph896011 pk1089
following is source of delphi
if any one help me much apprecated!
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, IdBaseComponent, IdComponent, IdTCPConnection,
IdTCPClient, IdHTTP, IdCookieManager, ExtCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
IdHTTP1: TIdHTTP;
Memo1: TMemo;
IdCookieManager1: TIdCookieManager;
lstAcct: TListBox;
result: TLabel;
Edit1: TEdit;
Timer1: TTimer;
procedure Button1Click(Sender: TObject);
//procedure FormCreate(Sender: TObject);
//procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
AccList: TStringList;
IdCookie: TIdCookieManager;
CookieList: TList;
StartCnt: Integer;
InputCnt: Integer;
WordList: TStringList;
WordNoList: TStringList;
WordCntList: TStringList;
StartTime: TDateTime;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
//temp: String;
lsttemp: TStringList;
sl : tstringlist;
//userId,userPass: string;
begin
InputCnt:= 0;
WordList := TStringList.Create;
CookieList := TList.create;
IdCookie := TIdCookieManager.Create(self);
if FileExists(ExtractFilePath(Application.ExeName) + 'account.txt') then
WordList.LoadFromFile(ExtractFilePath(Application.ExeName) + 'account.txt');
WordNoList:= TStringList.Create;
WordCntList := TStringList.Create;
lsttemp := TStringList.create;
sl :=Tstringlist.Create;
try
try
for i := 0 to WordList.Count -1 do
begin
ExtractStrings([' '], [' '], pchar(WordList[i]), lsttemp);
WordNoList.add(lsttemp[0]);
//ShowMessage(lsttemp[0]);
WordCntList.add(lsttemp[1]);
//ShowMessage(lsttemp[1]);
sl.Add('ID='+ lsttemp[0]);
sl.add('PWD=' + lsttemp[1]);
sl.add('SECCHK=0');
IdHTTP1.HandleRedirects := True;
IdHTTP1.Request.ContentType := 'application/x-www-form-urlencoded';
memo1.Text:=idhttp1.Post('http://user.buddybuddy.co.kr/Login/Login.asp',sl);
if pos('top.location =',Memo1.Text)> 0 then
begin
application.ProcessMessages;
ShowMessage('Alive Acc!');
//result.Caption := 'alive acc' ;
sleep(1000);
Edit1.Text := 'alive acc';
lsttemp.Clear;
Memo1.Text := '';
//memo1.Text := IdHTTP1.Get('https://user.buddybuddy.co.kr/Login/Logout.asp');
Sleep(1000);
end;
if pos('top.location =', memo1.Text) <> 1 then
begin
application.ProcessMessages;
ShowMessage('bad');
Edit1.Text := 'bad';
//edit1.Text := 'bad';
lsttemp.Clear;
memo1.Text := '';
sleep(1000) ;
end;
Edit1.Text := '';
end;
finally
lsttemp.free;
end;
StartCnt := lstAcct.items.Count;
StartTime := Now;
finally
sl.Free;
end;
end;
end.
Right before:
sl.Add('ID='+ lsttemp[0]);
Do:
sl.Clear;
On the first run your "SL" holds the two POST parameters, but unless you clear it on the second run, you just keep adding parameters, confusing the HTTP server you're trying to connect to!
That might not be your only problem, but that's surely one of the problems.