R
ranyang
Unregistered / Unconfirmed
GUEST, unregistred user!
这是我的代码:
全部:
unit U_main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxControls, cxContainer, cxEdit, cxGroupBox, Menus, ScktComp,
ShellApi, IniFiles, StdCtrls, ExtCtrls, msxmldom, XMLDoc,xmldom, XMLIntf,
IdBaseComponent, IdComponent, IdUDPBase, IdUDPServer, IdSocketHandle,
Grids, ValEdit, DBGridEh, DB, ADODB;
const
WM_BARICON=WM_USER+200;
type
TMainFrm = class(TForm)
CSocket: TClientSocket;
SSocket: TServerSocket;
CTimer: TTimer;
STimer: TTimer;
TCPSendXML: TXMLDocument;
CReceXML: TXMLDocument;
SSendXML: TXMLDocument;
TCPSocket: TServerSocket;
TCPTimer: TTimer;
UDPsocket: TIdUDPServer;
UDPTimer: TTimer;
UDPSendXML: TXMLDocument;
ADOCon: TADOConnection;
ADOGL: TADOQuery;
GroupBox1: TGroupBox;
CGroupBox: TLabel;
SGroupBox: TLabel;
TCPGroupBox: TLabel;
Link: TLabel;
UDPGroupBox: TLabel;
PopupMenu1: TPopupMenu;
N1: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure CSocketConnecting(Sender: TObject; Socket: TCustomWinSocket);
procedure CSocketDisconnect(Sender: TObject; Socket: TCustomWinSocket);
procedure CSocketError(Sender: TObject; Socket: TCustomWinSocket;
ErrorEvent: TErrorEvent; var ErrorCode: Integer);
procedure CSocketConnect(Sender: TObject; Socket: TCustomWinSocket);
procedure CTimerTimer(Sender: TObject);
procedure SSocketClientError(Sender: TObject; Socket: TCustomWinSocket;
ErrorEvent: TErrorEvent; var ErrorCode: Integer);
procedure STimerTimer(Sender: TObject);
procedure SSocketClientConnect(Sender: TObject;
Socket: TCustomWinSocket);
procedure SSocketClientRead(Sender: TObject; Socket: TCustomWinSocket);
procedure CSocketRead(Sender: TObject; Socket: TCustomWinSocket);
procedure TCPSocketClientConnect(Sender: TObject;
Socket: TCustomWinSocket);
procedure TCPTimerTimer(Sender: TObject);
procedure TCPSocketClientError(Sender: TObject;
Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
procedure TCPSocketClientDisconnect(Sender: TObject;
Socket: TCustomWinSocket);
procedure TCPSocketClientRead(Sender: TObject;
Socket: TCustomWinSocket);
procedure UDPTimerTimer(Sender: TObject);
procedure UDPsocketUDPRead(Sender: TObject; AData: TStream;
ABinding: TIdSocketHandle);
procedure ADOConBeforeConnect(Sender: TObject);
procedure GroupBox1DblClick(Sender: TObject);
procedure N1Click(Sender: TObject);
private
{ Private declarations }
//系统托盘化过程
procedure WMSysCommand(var Message: TMessage); message WM_SYSCOMMAND;
procedure WMBarIcon(var Message:TMessage);message WM_BARICON;
public
{ Public declarations }
SETTING_FILE: string;
procedure ManageportData(Str: string);
function equportisexist(equstr,portstr:string):Boolean;
function equisexist(str: string):Boolean;
function equtoport(str: string):integer;
function ReadIniFile(IniFileName,FirstDirectory,SecondDirectory:string):string; //读INI配置文件
procedure WriteIniFile(IniFileName,FirstDirectory,SecondDirectory,WriteName:string); //写INI配置文件
function LinkData():string;
end;
var
MainFrm: TMainFrm;
IniFile:TIniFile;
SockPool,TCpSockPool:TList;
implementation
{$R *.dfm}
uses u_socketset;
function TMainFrm.LinkData():string;//读取当前连接数
begin
try
ADOGL.Close;
ADOGL.SQL.Clear;
ADOGL.SQL.Text:='select * from [T_port]';
ADOGL.Open;
Result:=inttostr(ADOGL.RecordCount);
except
REsult:='0';
end;
end;
procedure TMainFrm.ManageportData(Str: string);//管理数据
begin
try
ADOGL.Close;
ADOGL.SQL.Clear;
ADOGL.SQL.Text:=str;
ADOGL.Execsql;
except
end;
end;
function TMainFrm.equportisexist(equstr,portstr:string):Boolean; //判断连接是否存在
begin
try
ADOGL.Close;
ADOGL.SQL.Clear;
ADOGL.SQL.Text:='select * from [T_port] where Fequnum='+quotedstr(equstr)+' and Fport='+quotedstr(portstr);
ADOGL.Open;
if ADOGL.RecordCount=1 then
Result:=True
else
Result:=False;
except
Result:=False;
end;
end;
function TMainFrm.equisexist(str: string):Boolean; //判断连接是否存在,,,
begin
try
ADOGL.Close;
ADOGL.SQL.Clear;
ADOGL.SQL.Text:='select * from [T_port] where Fequnum='+quotedstr(str);
ADOGL.Open;
if ADOGL.RecordCount=1 then
Result:=True
else
Result:=False;
except
Result:=False;
end;
end;
function TMainFrm.equtoport(str: string):integer; //返回有TCP连接的设备的相应的端口号,
begin
try
ADOGL.Close;
ADOGL.SQL.Clear;
ADOGL.SQL.Text:='select Fport from [T_port] where Fequnum='+quotedstr(str);
ADOGL.Open;
Result:=strtoint(copy(ADOGL.FieldByName('Fport').AsString,pos('#',ADOGL.FieldByName('Fport').AsString)+1,length(ADOGL.FieldByName('Fport').AsString)-pos('#',ADOGL.FieldByName('Fport').AsString)));
except
Result:=0;
end;
end;
procedure TMainFrm.WMBarIcon(var Message: TMessage);
var
lpDataNotifyIconData;
begin
if (Message.LParam = WM_LBUTTONDOWN) then
begin
//如果用户点击任务栏图标则将图标删除并回复窗口。
lpData := new(PNotifyIconDataA);
lpData.cbSize := 88;//SizeOf(PNotifyIconDataA);
lpData.Wnd := MainFrm.Handle;
lpData.hIcon := MainFrm.Icon.Handle;
lpData.uCallbackMessage := WM_BARICON;
lpData.uID :=0;
lpData.szTip := '短信收发机中转服务';
lpData.uFlags := NIF_ICON or NIF_MESSAGE or NIF_TIP;
Shell_NotifyIcon(NIM_DELETE,lpData);
dispose(lpData);
MainFrm.Visible := True;
end;
end;
procedure TMainFrm.WMSysCommand(var Message: TMessage);
var
lpDataNotifyIconData;
begin
if Message.WParam = SC_ICON then
begin
//如果用户最小化窗口则将窗口隐藏并在任务栏上添加图标
lpData := new(PNotifyIconDataA);
lpData.cbSize := 88;
lpData.Wnd := MainFrm.Handle;
lpData.hIcon := MainFrm.Icon.Handle;
lpData.uCallbackMessage := WM_BARICON;
lpData.uID :=0;
lpData.szTip := '短信收发机中转服务';
lpData.uFlags := NIF_ICON or NIF_MESSAGE or NIF_TIP;
Shell_NotifyIcon(NIM_ADD,lpData);
dispose(lpData);
MainFrm.Visible := False;
end
else
begin
//如果是其它的SystemCommand消息则调用系统缺省处理函数处理。
DefWindowProc(MainFrm.Handle,Message.Msg,Message.WParam,Message.LParam);
end;
end;
function TMainFrm.ReadIniFile(IniFileName, FirstDirectory,
SecondDirectory: string): string;
begin
IniFile:=TIniFile.Create(IniFileName);
result:=IniFile.ReadString(FirstDirectory,SecondDirectory,'');
IniFile.Free;
end;
procedure TMainFrm.WriteIniFile(IniFileName, FirstDirectory,
SecondDirectory, WriteName: string);
begin
IniFile:=TIniFile.Create(IniFileName);
IniFile.WriteString(FirstDirectory,SecondDirectory,WriteName);
IniFile.Free;
end;
procedure TMainFrm.FormCreate(Sender: TObject);
begin
SETTING_FILE:=copy(Application.ExeName,1,LastDelimiter('/',Application.ExeName))+'Config.ini';
SockPool:=TList.Create;
TCPSockPool:=Tlist.Create;
end;
procedure TMainFrm.FormShow(Sender: TObject);
begin
try
SSocket.Port:=StrToint(ReadIniFile(SETTING_FILE,'Serverport','SPort'));
SSocket.Active:=True;
SGroupBox.Caption:='ServerSocket is Running,Port:'+ReadIniFile(SETTING_FILE,'Serverport','SPort');
TCPSocket.Port:=StrToint(ReadIniFile(SETTING_FILE,'TCPport','TPort'));
TCPSocket.Active:=True;
TCPGroupBox.Caption:='TCPSocket is Running,Port:'+ReadIniFile(SETTING_FILE,'TCPport','TPort');
CSocket.Address:=ReadIniFile(SETTING_FILE,'Client','CAddr');
CSocket.Port:=StrToInt(ReadIniFile(SETTING_FILE,'Client','CPort'));
CSocket.Active:=True;
CGroupBox.Caption:='ClientSocket is Running,Address:'+ReadIniFile(SETTING_FILE,'Client','CAddr')+';Port:'+ReadIniFile(SETTING_FILE,'Client','CPort');
UDPSocket.DefaultPort:=StrToint(ReadIniFile(SETTING_FILE,'UDPport','UPort'));
UDPSocket.Active:=True;
UDPGroupBox.Caption:='UDPSocket is Running,Port:'+ReadIniFile(SETTING_FILE,'UDPport','UPort');
ManageportData('Delete from [T_port]');
Link.caption:='Link:'+LinkData;
except
end;
end;
procedure TMainFrm.CSocketConnecting(Sender: TObject;
Socket: TCustomWinSocket);
begin
CGroupBox.Caption:='ClientSocket is Connecting';
end;
procedure TMainFrm.CSocketDisconnect(Sender: TObject;
Socket: TCustomWinSocket);
begin
CGroupBox.Caption:='ClientSocket is Disconnect';
end;
procedure TMainFrm.CSocketError(Sender: TObject; Socket: TCustomWinSocket;
ErrorEvent: TErrorEvent; var ErrorCode: Integer);
begin
CGroupBox.Caption:='ClientSocket is Error';
end;
procedure TMainFrm.CSocketConnect(Sender: TObject;
Socket: TCustomWinSocket);
begin
CGroupBox.Caption:='ClientSocket is Running,Address:'+ReadIniFile(SETTING_FILE,'Client','CAddr')+';Port:'+ReadIniFile(SETTING_FILE,'Client','CPort');
end;
procedure TMainFrm.CTimerTimer(Sender: TObject);
begin
if CGroupBox.Caption = 'ClientSocket is Disconnect' then
begin
CSocket.Address:=ReadIniFile(SETTING_FILE,'Client','CAddr');
CSocket.Port:=StrToInt(ReadIniFile(SETTING_FILE,'Client','CPort'));
CSocket.Active:=True;
CGroupBox.Caption:='ClientSocket is Running,Address:'+ReadIniFile(SETTING_FILE,'Client','CAddr')+';Port:'+ReadIniFile(SETTING_FILE,'Client','CPort');
end;
end;
procedure TMainFrm.SSocketClientError(Sender: TObject;
Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
begin
SGroupBox.Caption:='ServerSocket is Error';
end;
procedure TMainFrm.STimerTimer(Sender: TObject);
begin
if SGroupBox.Caption = 'ServerSocket is Error' then
begin
SSocket.Active:=False;
SSocket.Port:=strtoint(ReadIniFile(SETTING_FILE,'Serverport','SPort'));
SSocket.Active:=True;
SGroupBox.Caption:='ServerSocket is Running,Port:'+ReadIniFile(SETTING_FILE,'Serverport','SPort');
end;
end;
procedure TMainFrm.SSocketClientConnect(Sender: TObject;
Socket: TCustomWinSocket);
begin
try
if SSocket.Socket.ActiveConnections < 3 then
begin
SockPool.Add(Socket);
end
else
begin
Socket.Close;
Socket.Free;
end;
except
TCustomWinSocket(SockPool[Socket.SocketHandle]).Close;
SockPool.Remove(SockPool[Socket.SocketHandle]);
end;
end;
procedure TMainFrm.SSocketClientRead(Sender: TObject;
Socket: TCustomWinSocket);
var
Root: IXMLNode;
begin //读到短信收发机的信息后发回到10110服务器!
SSendXML.Active := False;
SsendXML.XML.Text := Socket.ReceiveText;
SsendXML.Active := True;
Root:= SSendXML.DocumentElement;
Csocket.Socket.SendText(SsendXML.XML.Text);
end;
procedure TMainFrm.CSocketRead(Sender: TObject; Socket: TCustomWinSocket);
var
I: Integer;
Root: IXMLNode;
begin//读到10110的信息后发到指定
CReceXML.Active := False;
CReceXML.XML.Text := Socket.ReceiveText;
CreceXML.Active := True;
Root:= CReceXML.DocumentElement;
if (Root.ChildNodes['CodeType'].Text='GBK') or (Root.ChildNodes['CodeType'].Text='ASC') then
begin
for I := 0 to SSocket.Socket.ActiveConnections-1 do // Iterate
begin
TCustomWinSocket(SockPool).SendText(CReceXML.XML.Text);
end;
end
else
if Root.ChildNodes['CodeType'].Text='PDU-ASCII' then
begin
if equisexist(Root.ChildNodes['ID'].Text)=False then
begin
for I := 0 to SSocket.Socket.ActiveConnections-1 do // Iterate
begin
TCustomWinSocket(SockPool).SendText(CReceXML.XML.Text);
end;
end
else
if equisexist(Root.ChildNodes['ID'].Text)=True then
begin
for I := 0 to TCPSocket.Socket.ActiveConnections-1 do // Iterate
begin
if TCustomWinSocket(TCPSockPool).SocketHandle=equtoPort(Root.ChildNodes['ID'].Text) then
TCustomWinSocket(TCPSockPool).SendText(Root.ChildNodes['Content'].Text);
end;
end;
end;
end;
//处理设备TCP回传信息,返回到分发程序...
procedure TMainFrm.TCPSocketClientConnect(Sender: TObject;
Socket: TCustomWinSocket);
begin
try
TCPSockPool.Add(Socket);
socket.SendText('<C001>');
except
TCustomWinSocket(TCPSockPool[Socket.SocketHandle]).Close;
TCPSockPool.Remove(TCPSockPool[Socket.SocketHandle]);
end;
end;
procedure TMainFrm.TCPTimerTimer(Sender: TObject);
begin
if TCPGroupBox.Caption = 'TCPSocket is Error' then
begin
TCPSocket.Active:=False;
TCPSocket.Port:=strtoint(ReadIniFile(SETTING_FILE,'TCPport','TPort'));
TCPSocket.Active:=True;
TCPGroupBox.Caption:='TCPSocket is Running,Port:'+ReadIniFile(SETTING_FILE,'TCPport','TPort');
ManageportData('Delete from [T_port]');
Link.caption:='Link:'+LinkData;
end;
end;
procedure TMainFrm.TCPSocketClientError(Sender: TObject;
Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
begin //抓到异常,处理为不弹出任何东西![][][][][]
try
TCPGroupBox.Caption:='TCPSocket is Error';
except
end;
end;
procedure TMainFrm.TCPSocketClientDisconnect(Sender: TObject;
Socket: TCustomWinSocket);
begin
ManageportData('Delete From [T_port] where Fport='+quotedstr(StringReplace(Socket.RemoteAddress,'.','',[rfReplaceAll])+'#'+inttostr(Socket.SocketHandle)));
Link.caption:='Link:'+LinkData;
end;
procedure TMainFrm.TCPSocketClientRead(Sender: TObject;
Socket: TCustomWinSocket);
var
Root: IXMLNode;
mystr: string;
begin //读到设备回传信息后发回到10110服务器! Socket.ReceiveText
mystr:=socket.ReceiveText;
if Equisexist(Copy(mystr,1,pos(':',mystr)-1))=True then
begin //存在则考虑判断一下端口是否一致
if equPortisexist(Copy(mystr,1,pos(':',mystr)-1),StringReplace(Socket.RemoteAddress,'.','',[rfReplaceAll])+'#'+inttostr(Socket.SocketHandle))=True then
begin
TCPSendXML.Active := False;
TCPsendXML.FileName := 'Send.xml';
TCPsendXML.Active := True;
Root:= TCPSendXML.DocumentElement;
Root.ChildNodes['Time'].Text:=DateTimetostr(now);
Root.ChildNodes['TelNum'].Text:=Copy(mystr,1,pos(':',mystr)-1);
Root.ChildNodes['Content'].Text:=Copy(mystr,pos(':',mystr)+1,length(mystr)-pos(':',mystr));
Csocket.Socket.SendText(TCPsendXML.XML.Text);
end
else
if equPortisexist(Copy(mystr,1,pos(':',mystr)-1),StringReplace(Socket.RemoteAddress,'.','',[rfReplaceAll])+'#'+inttostr(Socket.SocketHandle))=False then
begin
ManageportData('update [T_port] set Fport='+quotedstr(StringReplace(Socket.RemoteAddress,'.','',[rfReplaceAll])+'#'+inttostr(Socket.SocketHandle))+' where Fequnum='+quotedstr(Copy(mystr,1,pos(':',mystr)-1)));
Link.caption:='Link:'+LinkData;
end;
end
else
if Equisexist(Copy(mystr,1,pos(':',mystr)-1))=False then
begin
ManageportData('insert into [T_port](Fequnum,Fport)values('+quotedstr(Copy(mystr,1,pos(':',mystr)-1))+','+quotedstr(StringReplace(Socket.RemoteAddress,'.','',[rfReplaceAll])+'#'+inttostr(Socket.SocketHandle))+')');
Link.caption:='Link:'+LinkData;
end;
end;
//UDP
procedure TMainFrm.UDPTimerTimer(Sender: TObject);
begin
if UDPGroupBox.Caption = 'UDPSocket is Error' then
begin
UDPSocket.Active:=False;
UDPSocket.DefaultPort:=strtoint(ReadIniFile(SETTING_FILE,'UDPport','UPort'));
UDPSocket.Active:=True;
UDPGroupBox.Caption:='UDPSocket is Running,Port:'+ReadIniFile(SETTING_FILE,'UDPport','UPort');
end;
end;
procedure TMainFrm.UDPsocketUDPRead(Sender: TObject; AData: TStream;
ABinding: TIdSocketHandle);
var
Mystr: TStringStream;
Root: IXMLNode;
begin //读到设备回传信息后发回到10110服务器!
Mystr:= TStringStream.Create('');
try
Mystr.CopyFrom(AData, AData.Size);
UDPSendXML.Active := False;
UDPsendXML.FileName := 'Send.xml';
UDPsendXML.Active := True;
Root:= UDPSendXML.DocumentElement;
Root.ChildNodes['Time'].Text:=DateTimetostr(now);
Root.ChildNodes['TelNum'].Text:=Copy(mystr.DataString,1,pos(':',mystr.DataString)-1);
Root.ChildNodes['Content'].Text:=Copy(mystr.DataString,pos(':',mystr.DataString)+1,length(mystr.DataString)-pos(':',mystr.DataString));
Csocket.Socket.SendText(UDPsendXML.XML.Text);
finally
Mystr.Free;
end;
end;
procedure TMainFrm.ADOConBeforeConnect(Sender: TObject);
begin
ADOCon.ConnectionString:='Provider=Microsoft.Jet.OLEDB.4.0;User ID=Admin;Data Source='+copy(Application.ExeName,1,LastDelimiter('/',Application.ExeName))+'topeakport.mdb;Persist Security Info=False';
end;
procedure TMainFrm.GroupBox1DblClick(Sender: TObject);
begin
try
Application.CreateForm(TsetFrm, SetFrm);
SetFrm.ShowModal;
finally
SetFrm.Free;
end;
end;
procedure TMainFrm.N1Click(Sender: TObject);
begin
showmessage('!');
end;
end.
现在我想让clientsocket连接tcpsocket后,异常退出后,不在上面的四个[]处的情况出现!!!!
另外:我的程序运行一段时间后,会弹出一个“list index out of bounds (-1)”问题!!!
全部:
unit U_main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxControls, cxContainer, cxEdit, cxGroupBox, Menus, ScktComp,
ShellApi, IniFiles, StdCtrls, ExtCtrls, msxmldom, XMLDoc,xmldom, XMLIntf,
IdBaseComponent, IdComponent, IdUDPBase, IdUDPServer, IdSocketHandle,
Grids, ValEdit, DBGridEh, DB, ADODB;
const
WM_BARICON=WM_USER+200;
type
TMainFrm = class(TForm)
CSocket: TClientSocket;
SSocket: TServerSocket;
CTimer: TTimer;
STimer: TTimer;
TCPSendXML: TXMLDocument;
CReceXML: TXMLDocument;
SSendXML: TXMLDocument;
TCPSocket: TServerSocket;
TCPTimer: TTimer;
UDPsocket: TIdUDPServer;
UDPTimer: TTimer;
UDPSendXML: TXMLDocument;
ADOCon: TADOConnection;
ADOGL: TADOQuery;
GroupBox1: TGroupBox;
CGroupBox: TLabel;
SGroupBox: TLabel;
TCPGroupBox: TLabel;
Link: TLabel;
UDPGroupBox: TLabel;
PopupMenu1: TPopupMenu;
N1: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure CSocketConnecting(Sender: TObject; Socket: TCustomWinSocket);
procedure CSocketDisconnect(Sender: TObject; Socket: TCustomWinSocket);
procedure CSocketError(Sender: TObject; Socket: TCustomWinSocket;
ErrorEvent: TErrorEvent; var ErrorCode: Integer);
procedure CSocketConnect(Sender: TObject; Socket: TCustomWinSocket);
procedure CTimerTimer(Sender: TObject);
procedure SSocketClientError(Sender: TObject; Socket: TCustomWinSocket;
ErrorEvent: TErrorEvent; var ErrorCode: Integer);
procedure STimerTimer(Sender: TObject);
procedure SSocketClientConnect(Sender: TObject;
Socket: TCustomWinSocket);
procedure SSocketClientRead(Sender: TObject; Socket: TCustomWinSocket);
procedure CSocketRead(Sender: TObject; Socket: TCustomWinSocket);
procedure TCPSocketClientConnect(Sender: TObject;
Socket: TCustomWinSocket);
procedure TCPTimerTimer(Sender: TObject);
procedure TCPSocketClientError(Sender: TObject;
Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
procedure TCPSocketClientDisconnect(Sender: TObject;
Socket: TCustomWinSocket);
procedure TCPSocketClientRead(Sender: TObject;
Socket: TCustomWinSocket);
procedure UDPTimerTimer(Sender: TObject);
procedure UDPsocketUDPRead(Sender: TObject; AData: TStream;
ABinding: TIdSocketHandle);
procedure ADOConBeforeConnect(Sender: TObject);
procedure GroupBox1DblClick(Sender: TObject);
procedure N1Click(Sender: TObject);
private
{ Private declarations }
//系统托盘化过程
procedure WMSysCommand(var Message: TMessage); message WM_SYSCOMMAND;
procedure WMBarIcon(var Message:TMessage);message WM_BARICON;
public
{ Public declarations }
SETTING_FILE: string;
procedure ManageportData(Str: string);
function equportisexist(equstr,portstr:string):Boolean;
function equisexist(str: string):Boolean;
function equtoport(str: string):integer;
function ReadIniFile(IniFileName,FirstDirectory,SecondDirectory:string):string; //读INI配置文件
procedure WriteIniFile(IniFileName,FirstDirectory,SecondDirectory,WriteName:string); //写INI配置文件
function LinkData():string;
end;
var
MainFrm: TMainFrm;
IniFile:TIniFile;
SockPool,TCpSockPool:TList;
implementation
{$R *.dfm}
uses u_socketset;
function TMainFrm.LinkData():string;//读取当前连接数
begin
try
ADOGL.Close;
ADOGL.SQL.Clear;
ADOGL.SQL.Text:='select * from [T_port]';
ADOGL.Open;
Result:=inttostr(ADOGL.RecordCount);
except
REsult:='0';
end;
end;
procedure TMainFrm.ManageportData(Str: string);//管理数据
begin
try
ADOGL.Close;
ADOGL.SQL.Clear;
ADOGL.SQL.Text:=str;
ADOGL.Execsql;
except
end;
end;
function TMainFrm.equportisexist(equstr,portstr:string):Boolean; //判断连接是否存在
begin
try
ADOGL.Close;
ADOGL.SQL.Clear;
ADOGL.SQL.Text:='select * from [T_port] where Fequnum='+quotedstr(equstr)+' and Fport='+quotedstr(portstr);
ADOGL.Open;
if ADOGL.RecordCount=1 then
Result:=True
else
Result:=False;
except
Result:=False;
end;
end;
function TMainFrm.equisexist(str: string):Boolean; //判断连接是否存在,,,
begin
try
ADOGL.Close;
ADOGL.SQL.Clear;
ADOGL.SQL.Text:='select * from [T_port] where Fequnum='+quotedstr(str);
ADOGL.Open;
if ADOGL.RecordCount=1 then
Result:=True
else
Result:=False;
except
Result:=False;
end;
end;
function TMainFrm.equtoport(str: string):integer; //返回有TCP连接的设备的相应的端口号,
begin
try
ADOGL.Close;
ADOGL.SQL.Clear;
ADOGL.SQL.Text:='select Fport from [T_port] where Fequnum='+quotedstr(str);
ADOGL.Open;
Result:=strtoint(copy(ADOGL.FieldByName('Fport').AsString,pos('#',ADOGL.FieldByName('Fport').AsString)+1,length(ADOGL.FieldByName('Fport').AsString)-pos('#',ADOGL.FieldByName('Fport').AsString)));
except
Result:=0;
end;
end;
procedure TMainFrm.WMBarIcon(var Message: TMessage);
var
lpDataNotifyIconData;
begin
if (Message.LParam = WM_LBUTTONDOWN) then
begin
//如果用户点击任务栏图标则将图标删除并回复窗口。
lpData := new(PNotifyIconDataA);
lpData.cbSize := 88;//SizeOf(PNotifyIconDataA);
lpData.Wnd := MainFrm.Handle;
lpData.hIcon := MainFrm.Icon.Handle;
lpData.uCallbackMessage := WM_BARICON;
lpData.uID :=0;
lpData.szTip := '短信收发机中转服务';
lpData.uFlags := NIF_ICON or NIF_MESSAGE or NIF_TIP;
Shell_NotifyIcon(NIM_DELETE,lpData);
dispose(lpData);
MainFrm.Visible := True;
end;
end;
procedure TMainFrm.WMSysCommand(var Message: TMessage);
var
lpDataNotifyIconData;
begin
if Message.WParam = SC_ICON then
begin
//如果用户最小化窗口则将窗口隐藏并在任务栏上添加图标
lpData := new(PNotifyIconDataA);
lpData.cbSize := 88;
lpData.Wnd := MainFrm.Handle;
lpData.hIcon := MainFrm.Icon.Handle;
lpData.uCallbackMessage := WM_BARICON;
lpData.uID :=0;
lpData.szTip := '短信收发机中转服务';
lpData.uFlags := NIF_ICON or NIF_MESSAGE or NIF_TIP;
Shell_NotifyIcon(NIM_ADD,lpData);
dispose(lpData);
MainFrm.Visible := False;
end
else
begin
//如果是其它的SystemCommand消息则调用系统缺省处理函数处理。
DefWindowProc(MainFrm.Handle,Message.Msg,Message.WParam,Message.LParam);
end;
end;
function TMainFrm.ReadIniFile(IniFileName, FirstDirectory,
SecondDirectory: string): string;
begin
IniFile:=TIniFile.Create(IniFileName);
result:=IniFile.ReadString(FirstDirectory,SecondDirectory,'');
IniFile.Free;
end;
procedure TMainFrm.WriteIniFile(IniFileName, FirstDirectory,
SecondDirectory, WriteName: string);
begin
IniFile:=TIniFile.Create(IniFileName);
IniFile.WriteString(FirstDirectory,SecondDirectory,WriteName);
IniFile.Free;
end;
procedure TMainFrm.FormCreate(Sender: TObject);
begin
SETTING_FILE:=copy(Application.ExeName,1,LastDelimiter('/',Application.ExeName))+'Config.ini';
SockPool:=TList.Create;
TCPSockPool:=Tlist.Create;
end;
procedure TMainFrm.FormShow(Sender: TObject);
begin
try
SSocket.Port:=StrToint(ReadIniFile(SETTING_FILE,'Serverport','SPort'));
SSocket.Active:=True;
SGroupBox.Caption:='ServerSocket is Running,Port:'+ReadIniFile(SETTING_FILE,'Serverport','SPort');
TCPSocket.Port:=StrToint(ReadIniFile(SETTING_FILE,'TCPport','TPort'));
TCPSocket.Active:=True;
TCPGroupBox.Caption:='TCPSocket is Running,Port:'+ReadIniFile(SETTING_FILE,'TCPport','TPort');
CSocket.Address:=ReadIniFile(SETTING_FILE,'Client','CAddr');
CSocket.Port:=StrToInt(ReadIniFile(SETTING_FILE,'Client','CPort'));
CSocket.Active:=True;
CGroupBox.Caption:='ClientSocket is Running,Address:'+ReadIniFile(SETTING_FILE,'Client','CAddr')+';Port:'+ReadIniFile(SETTING_FILE,'Client','CPort');
UDPSocket.DefaultPort:=StrToint(ReadIniFile(SETTING_FILE,'UDPport','UPort'));
UDPSocket.Active:=True;
UDPGroupBox.Caption:='UDPSocket is Running,Port:'+ReadIniFile(SETTING_FILE,'UDPport','UPort');
ManageportData('Delete from [T_port]');
Link.caption:='Link:'+LinkData;
except
end;
end;
procedure TMainFrm.CSocketConnecting(Sender: TObject;
Socket: TCustomWinSocket);
begin
CGroupBox.Caption:='ClientSocket is Connecting';
end;
procedure TMainFrm.CSocketDisconnect(Sender: TObject;
Socket: TCustomWinSocket);
begin
CGroupBox.Caption:='ClientSocket is Disconnect';
end;
procedure TMainFrm.CSocketError(Sender: TObject; Socket: TCustomWinSocket;
ErrorEvent: TErrorEvent; var ErrorCode: Integer);
begin
CGroupBox.Caption:='ClientSocket is Error';
end;
procedure TMainFrm.CSocketConnect(Sender: TObject;
Socket: TCustomWinSocket);
begin
CGroupBox.Caption:='ClientSocket is Running,Address:'+ReadIniFile(SETTING_FILE,'Client','CAddr')+';Port:'+ReadIniFile(SETTING_FILE,'Client','CPort');
end;
procedure TMainFrm.CTimerTimer(Sender: TObject);
begin
if CGroupBox.Caption = 'ClientSocket is Disconnect' then
begin
CSocket.Address:=ReadIniFile(SETTING_FILE,'Client','CAddr');
CSocket.Port:=StrToInt(ReadIniFile(SETTING_FILE,'Client','CPort'));
CSocket.Active:=True;
CGroupBox.Caption:='ClientSocket is Running,Address:'+ReadIniFile(SETTING_FILE,'Client','CAddr')+';Port:'+ReadIniFile(SETTING_FILE,'Client','CPort');
end;
end;
procedure TMainFrm.SSocketClientError(Sender: TObject;
Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
begin
SGroupBox.Caption:='ServerSocket is Error';
end;
procedure TMainFrm.STimerTimer(Sender: TObject);
begin
if SGroupBox.Caption = 'ServerSocket is Error' then
begin
SSocket.Active:=False;
SSocket.Port:=strtoint(ReadIniFile(SETTING_FILE,'Serverport','SPort'));
SSocket.Active:=True;
SGroupBox.Caption:='ServerSocket is Running,Port:'+ReadIniFile(SETTING_FILE,'Serverport','SPort');
end;
end;
procedure TMainFrm.SSocketClientConnect(Sender: TObject;
Socket: TCustomWinSocket);
begin
try
if SSocket.Socket.ActiveConnections < 3 then
begin
SockPool.Add(Socket);
end
else
begin
Socket.Close;
Socket.Free;
end;
except
TCustomWinSocket(SockPool[Socket.SocketHandle]).Close;
SockPool.Remove(SockPool[Socket.SocketHandle]);
end;
end;
procedure TMainFrm.SSocketClientRead(Sender: TObject;
Socket: TCustomWinSocket);
var
Root: IXMLNode;
begin //读到短信收发机的信息后发回到10110服务器!
SSendXML.Active := False;
SsendXML.XML.Text := Socket.ReceiveText;
SsendXML.Active := True;
Root:= SSendXML.DocumentElement;
Csocket.Socket.SendText(SsendXML.XML.Text);
end;
procedure TMainFrm.CSocketRead(Sender: TObject; Socket: TCustomWinSocket);
var
I: Integer;
Root: IXMLNode;
begin//读到10110的信息后发到指定
CReceXML.Active := False;
CReceXML.XML.Text := Socket.ReceiveText;
CreceXML.Active := True;
Root:= CReceXML.DocumentElement;
if (Root.ChildNodes['CodeType'].Text='GBK') or (Root.ChildNodes['CodeType'].Text='ASC') then
begin
for I := 0 to SSocket.Socket.ActiveConnections-1 do // Iterate
begin
TCustomWinSocket(SockPool).SendText(CReceXML.XML.Text);
end;
end
else
if Root.ChildNodes['CodeType'].Text='PDU-ASCII' then
begin
if equisexist(Root.ChildNodes['ID'].Text)=False then
begin
for I := 0 to SSocket.Socket.ActiveConnections-1 do // Iterate
begin
TCustomWinSocket(SockPool).SendText(CReceXML.XML.Text);
end;
end
else
if equisexist(Root.ChildNodes['ID'].Text)=True then
begin
for I := 0 to TCPSocket.Socket.ActiveConnections-1 do // Iterate
begin
if TCustomWinSocket(TCPSockPool).SocketHandle=equtoPort(Root.ChildNodes['ID'].Text) then
TCustomWinSocket(TCPSockPool).SendText(Root.ChildNodes['Content'].Text);
end;
end;
end;
end;
//处理设备TCP回传信息,返回到分发程序...
procedure TMainFrm.TCPSocketClientConnect(Sender: TObject;
Socket: TCustomWinSocket);
begin
try
TCPSockPool.Add(Socket);
socket.SendText('<C001>');
except
TCustomWinSocket(TCPSockPool[Socket.SocketHandle]).Close;
TCPSockPool.Remove(TCPSockPool[Socket.SocketHandle]);
end;
end;
procedure TMainFrm.TCPTimerTimer(Sender: TObject);
begin
if TCPGroupBox.Caption = 'TCPSocket is Error' then
begin
TCPSocket.Active:=False;
TCPSocket.Port:=strtoint(ReadIniFile(SETTING_FILE,'TCPport','TPort'));
TCPSocket.Active:=True;
TCPGroupBox.Caption:='TCPSocket is Running,Port:'+ReadIniFile(SETTING_FILE,'TCPport','TPort');
ManageportData('Delete from [T_port]');
Link.caption:='Link:'+LinkData;
end;
end;
procedure TMainFrm.TCPSocketClientError(Sender: TObject;
Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
begin //抓到异常,处理为不弹出任何东西![][][][][]
try
TCPGroupBox.Caption:='TCPSocket is Error';
except
end;
end;
procedure TMainFrm.TCPSocketClientDisconnect(Sender: TObject;
Socket: TCustomWinSocket);
begin
ManageportData('Delete From [T_port] where Fport='+quotedstr(StringReplace(Socket.RemoteAddress,'.','',[rfReplaceAll])+'#'+inttostr(Socket.SocketHandle)));
Link.caption:='Link:'+LinkData;
end;
procedure TMainFrm.TCPSocketClientRead(Sender: TObject;
Socket: TCustomWinSocket);
var
Root: IXMLNode;
mystr: string;
begin //读到设备回传信息后发回到10110服务器! Socket.ReceiveText
mystr:=socket.ReceiveText;
if Equisexist(Copy(mystr,1,pos(':',mystr)-1))=True then
begin //存在则考虑判断一下端口是否一致
if equPortisexist(Copy(mystr,1,pos(':',mystr)-1),StringReplace(Socket.RemoteAddress,'.','',[rfReplaceAll])+'#'+inttostr(Socket.SocketHandle))=True then
begin
TCPSendXML.Active := False;
TCPsendXML.FileName := 'Send.xml';
TCPsendXML.Active := True;
Root:= TCPSendXML.DocumentElement;
Root.ChildNodes['Time'].Text:=DateTimetostr(now);
Root.ChildNodes['TelNum'].Text:=Copy(mystr,1,pos(':',mystr)-1);
Root.ChildNodes['Content'].Text:=Copy(mystr,pos(':',mystr)+1,length(mystr)-pos(':',mystr));
Csocket.Socket.SendText(TCPsendXML.XML.Text);
end
else
if equPortisexist(Copy(mystr,1,pos(':',mystr)-1),StringReplace(Socket.RemoteAddress,'.','',[rfReplaceAll])+'#'+inttostr(Socket.SocketHandle))=False then
begin
ManageportData('update [T_port] set Fport='+quotedstr(StringReplace(Socket.RemoteAddress,'.','',[rfReplaceAll])+'#'+inttostr(Socket.SocketHandle))+' where Fequnum='+quotedstr(Copy(mystr,1,pos(':',mystr)-1)));
Link.caption:='Link:'+LinkData;
end;
end
else
if Equisexist(Copy(mystr,1,pos(':',mystr)-1))=False then
begin
ManageportData('insert into [T_port](Fequnum,Fport)values('+quotedstr(Copy(mystr,1,pos(':',mystr)-1))+','+quotedstr(StringReplace(Socket.RemoteAddress,'.','',[rfReplaceAll])+'#'+inttostr(Socket.SocketHandle))+')');
Link.caption:='Link:'+LinkData;
end;
end;
//UDP
procedure TMainFrm.UDPTimerTimer(Sender: TObject);
begin
if UDPGroupBox.Caption = 'UDPSocket is Error' then
begin
UDPSocket.Active:=False;
UDPSocket.DefaultPort:=strtoint(ReadIniFile(SETTING_FILE,'UDPport','UPort'));
UDPSocket.Active:=True;
UDPGroupBox.Caption:='UDPSocket is Running,Port:'+ReadIniFile(SETTING_FILE,'UDPport','UPort');
end;
end;
procedure TMainFrm.UDPsocketUDPRead(Sender: TObject; AData: TStream;
ABinding: TIdSocketHandle);
var
Mystr: TStringStream;
Root: IXMLNode;
begin //读到设备回传信息后发回到10110服务器!
Mystr:= TStringStream.Create('');
try
Mystr.CopyFrom(AData, AData.Size);
UDPSendXML.Active := False;
UDPsendXML.FileName := 'Send.xml';
UDPsendXML.Active := True;
Root:= UDPSendXML.DocumentElement;
Root.ChildNodes['Time'].Text:=DateTimetostr(now);
Root.ChildNodes['TelNum'].Text:=Copy(mystr.DataString,1,pos(':',mystr.DataString)-1);
Root.ChildNodes['Content'].Text:=Copy(mystr.DataString,pos(':',mystr.DataString)+1,length(mystr.DataString)-pos(':',mystr.DataString));
Csocket.Socket.SendText(UDPsendXML.XML.Text);
finally
Mystr.Free;
end;
end;
procedure TMainFrm.ADOConBeforeConnect(Sender: TObject);
begin
ADOCon.ConnectionString:='Provider=Microsoft.Jet.OLEDB.4.0;User ID=Admin;Data Source='+copy(Application.ExeName,1,LastDelimiter('/',Application.ExeName))+'topeakport.mdb;Persist Security Info=False';
end;
procedure TMainFrm.GroupBox1DblClick(Sender: TObject);
begin
try
Application.CreateForm(TsetFrm, SetFrm);
SetFrm.ShowModal;
finally
SetFrm.Free;
end;
end;
procedure TMainFrm.N1Click(Sender: TObject);
begin
showmessage('!');
end;
end.
现在我想让clientsocket连接tcpsocket后,异常退出后,不在上面的四个[]处的情况出现!!!!
另外:我的程序运行一段时间后,会弹出一个“list index out of bounds (-1)”问题!!!