delphi一个用socket封装UDPTCP通信的例子.doc_第1页
delphi一个用socket封装UDPTCP通信的例子.doc_第2页
delphi一个用socket封装UDPTCP通信的例子.doc_第3页
delphi一个用socket封装UDPTCP通信的例子.doc_第4页
delphi一个用socket封装UDPTCP通信的例子.doc_第5页
已阅读5页,还剩6页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

unitUnitTCPUDP;interfaceusesWindows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,Dialogs,StdCtrls,WinSock,ExtCtrls,ComCtrls,inifiles,StrUtils;constWM_SOCK=WM_USER+82;自定义windows消息/在tcp服务器方式下,WM_SOCK为监听消息/WM_SOCK+1到WM_SOCK+MAX_ACCEPT为与连接客户端进行通讯时的消息MAX_ACCEPT=100;FD_SET=MAX_ACCEPT;typeTFormTCPUDP=class(TForm)BtnSend:TButton;MemoReceive:TMemo;EditSend:TEdit;Label2:TLabel;Label3:TLabel;Bevel2:TBevel;STOpCode:TStaticText;STIndex:TStaticText;STCommand:TStaticText;GroupBox1:TGroupBox;GroupBox2:TGroupBox;GroupBox3:TGroupBox;RBTCP:TRadioButton;RBUDP:TRadioButton;Panel1:TPanel;RBClient:TRadioButton;RBServer:TRadioButton;GroupBox4:TGroupBox;BtnConnect:TButton;BtnClose:TButton;Bevel1:TBevel;StatusBar1:TStatusBar;PanelDest:TPanel;Label4:TLabel;EditRemoteHost:TEdit;Label5:TLabel;EditRemotePort:TEdit;Label6:TLabel;CmbSendTo:TComboBox;Label7:TLabel;PanelLocal:TPanel;ChkBind:TCheckBox;EditHostPort:TEdit;Label1:TLabel;procedureBtnSendClick(Sender:TObject);procedureBtnConnectClick(Sender:TObject);procedureRBTCPClick(Sender:TObject);procedureRBUDPClick(Sender:TObject);procedureBtnCloseClick(Sender:TObject);procedureFormClose(Sender:TObject;varAction:TCloseAction);procedureRBClientClick(Sender:TObject);procedureRBServerClick(Sender:TObject);procedureChkBindClick(Sender:TObject);procedureFormCreate(Sender:TObject);procedureEditHostPortChange(Sender:TObject);procedureEditRemoteHostChange(Sender:TObject);procedureEditRemotePortChange(Sender:TObject);procedureFormActivate(Sender:TObject);procedureCmbSendToKeyPress(Sender:TObject;varKey:Char);消息接送privatePrivatedeclarationsFirstFlag:Boolean;INIPath:String;procedureReadData(varMessage:TMessage);functionReadTCPUDPIni():boolean;/读取配置信息procedureWriteIniStr(FileName:String;section:string;Ident:string;StringValue:string);/写系统信息procedureWriteIniBool(FileName:String;section:string;Ident:string;BoolValue:Boolean);/写系统信息protectedProtecteddeclarationsotherfieldsandmethodsprocedurewndproc(varmessage:Tmessage);override;publicPublicdeclarationsend;constDATA_LENGTH=120;/数据长度typeTUDPaction=packedrecordopcode:byte;/操作码index:word;/序列号Command:byte;/命令字data:array0.(DATA_LENGTH-1)ofchar;/数据end;varFormTCPUDP:TFormTCPUDP;AcceptSock:Array0.MAX_ACCEPTOFTsocket;FSockAccept:Array0.MAX_ACCEPTOFTSockAddrIn;AcceptSockFlag:Array0.MAX_ACCEPTOFboolean;AcceptNum:integer=0;FSockLocal:TSockAddrIn;PackageID:integer=0;/包序号BindFlag:Boolean=true;TcpFlag:Boolean=false;ServerFlag:Boolean=false;functionWinSockInital(Handle:HWnd):bool;ProcedureWinSockClose();implementation$R*.dfm始化SOCKETfunctionWinSockInital(Handle:HWnd):bool;varTempWSAData:TWSAData;i:integer;beginresult:=false;1初始化SOCKETifWSAStartup(2,TempWSAData)=1then/2表示启用winsock2exit;若是用UDP通信,则用ifTcpFlagthenAcceptSock0:=Socket(AF_INET,SOCK_STREAM,0)elseAcceptSock0:=Socket(AF_INET,SOCK_DGRAM,0);ifAcceptSock0=SOCKET_ERRORthenexit;if(BindFlagandnottcpflag)or(Serverflagandtcpflag)thenifbind(AcceptSock0,FSockLocal,sizeof(FSockLocal)0thenbeginWinSockClose();exit;end;ifTcpflagthenifServerflagthenbeginifListen(AcceptSock0,1)0then/等待连接队列的最大长度为1begin WinSockClose();exit;end;endelseifconnect(AcceptSock0,FSockAccept0,sizeof(FSockAccept0)0thenbeginWinSockClose();exit;end;FD_READ在读就绪的时候,产生WM_SOCK自定义消息号ifnotTcpFlagthenWSAAsyncSelect(AcceptSock0,Handle,WM_SOCK,FD_READ)elseifServerflagthenWSAAsyncSelect(AcceptSock0,Handle,WM_SOCK,FD_READorFD_ACCEPTorFD_CLOSE)elseWSAAsyncSelect(AcceptSock0,Handle,WM_SOCK,FD_READorFD_CLOSE);Result:=true;end;关闭SOCKETProcedureWinSockClose();vari:integer;beginfori:=1toMAX_ACCEPTDOifAcceptSockFlagithenbeginCloseSocket(AcceptSocki);AcceptSockFlagi:=false;end;CloseSocket(AcceptSock0);closesocket函数用来关闭一个描述符为AcceptSock0套接字WSACleanup;end;functionTFormTCPUDP.ReadTCPUDPIni():boolean;varti:TiniFile;beginti:=TIniFile.Create(INIPath+TCPUDP.ini);EditHostPort.text:=ti.ReadString(Setting,LocalPort,);ChkBind.Checked:=ti.ReadBool(Setting,BindStatus,false);EditRemotePort.text:=ti.ReadString(Setting,RemotePort,);EditRemoteHost.text:=ti.ReadString(Setting,RemoteHost,);RBTCP.Checked:=ti.ReadBool(Setting,TCPStatus,false);RBUDP.Checked:=notRBTCP.Checked;RBServer.Checked:=ti.ReadBool(Setting,ServerStatus,false);RBClient.Checked:=notRBServer.Checked;end;procedureTFormTCPUDP.WriteIniStr(FileName:String;Section:string;Ident:string;StringValue:string);varti:TiniFile;beginti:=TIniFile.Create(FileName);ti.writestring(section,Ident,StringValue);ti.Free;end;procedureTFormTCPUDP.WriteIniBool(FileName:String;Section:string;Ident:string;BoolValue:Boolean);varti:TiniFile;beginti:=TIniFile.Create(FileName);ti.writebool(section,Ident,BoolValue);ti.Free;end;procedureTFormTCPUDP.BtnSendClick(Sender:TObject);varSEND_PACKAGE:TUDPaction;/数据发送i:integer;s:String;beginFillchar(SEND_PACKAGE.data,Data_Length,chr(0);SEND_PACKAGE.data0:=1;SEND_PACKAGE.data1:=2;SEND_PACKAGE.data2:=3;SEND_PACKAGE.opcode:=2;SEND_PACKAGE.index:=PackageID;SEND_PACKAGE.Command:=3;s:=editsend.Text;fori:=0tolength(EditSend.Text)-1doSEND_PACKAGE.datai:=si+1;PackageID:=PackageID+1;ifnot(TcpflagandServerflag)thensendto(AcceptSock0,SEND_PACKAGE,sizeof(SEND_PACKAGE),0,FSockAccept0,sizeof(FSockAccept0)elseifAcceptNum=0thenApplication.MessageBox(没有一个客户端和您建立连接,信息提示,MB_OK)elsebegini:=pos(,CmbSendto.Text);ifi0thenbegini:=strtoint(MidStr(CmbSendTo.Text,8,i-8);sendto(AcceptSocki,SEND_PACKAGE,sizeof(SEND_PACKAGE),0,FSockAccepti,sizeof(FSockAccepti);endelseApplication.MessageBox(您没有选择发送方,错误提示,MB_OK);end;/sendto(AcceptSock0,NbtstatPacket,50,0,FSockAccept0,sizeof(FSockAccept0);end;procedureTFormTCPUDP.BtnConnectClick(Sender:TObject);vars:String;i:integer;begins:=正在建立连接.;StatusBar1.Panels0.Text:=s;Application.ProcessMessages;FSockLocal.sin_family:=AF_INET;FSockLocal.sin_port:=htons(strtoint(EditHostport.Text);FSockAccept0.sin_family:=AF_INET;FSockAccept0.sin_port:=htons(strtoint(EditRemoteport.Text);FSockAccept0.SIn_Addr.S_addr:=inet_addr(PChar(EditRemoteHost.Text);/inet_addr(pchar(IP);ifWinSockInital(FormTCPUDP.Handle)thenbeginBtnConnect.Enabled:=false;BtnClose.Enabled:=true;BtnSend.Enabled:=true;s:=连接成功!;ifChkBind.Checkedthens:=s+,-绑定端口;ifRBTcp.Checkedthenbegins:=s+,-TCP方式;ifRBServer.Checkedthens:=s+,-服务端elses:=s+,-客户端;endelses:=s+,-UDP方式;iftcpflagandServerflagthenbeginAcceptNum:=0;CmbSendto.Clear;StatusBar1.Panels2.Text:=共有:+inttostr(AcceptNum)+个连接;end;endelsebeginfori:=0toStatusBar1.Panels.count-1doStatusBar1.Panelsi.Text:=;s:=创建套接字失败!;end;StatusBar1.Panels0.Text:=s;end;procedureTFormTCPUDP.wndproc(varMessage:TMessage);beginif(Message.Msg=WM_SOCK)and(Message.Msg0thenbeginStatusBar1.Panels0.Text:=收到来自ip地址:+inet_ntoa(FSockAcceptIndex.sin_addr)+端口:+inttostr(ntohs(FSockAcceptIndex.sin_port)+的数据;StOpCode.Caption:=format(%.2d,Receive_PACKAGE.opCode);StIndex.Caption:=format(%d,Receive_PACKAGE.Index);StCommand.Caption:=format(%.2d,Receive_PACKAGE.Command);MemoReceive.Lines.Add(StrPas(Receive_PACKAGE.data)end;endelseifEvent=FD_ACCEPTthenbeginfori:=1toMAX_ACCEPTDOifnotAcceptSockFlagithenbeginflen:=Sizeof(FSockAccepti);AcceptSocki:=accept(AcceptSock0,FSockAccepti,flen);WSAAsyncSelect(AcceptSocki,Handle,WM_SOCK+i,FD_READorFD_CLOSE);AcceptSockFlagi:=true;AcceptNum:=AcceptNum+1;CmbSendto.Items.Add(套接口:+inttostr(i)+地址:+inet_ntoa(FSockAccepti.sin_addr)+端口:+inttostr(ntohs(FSockAccepti.sin_port);break;end;StatusBar1.Panels2.Text:=共有:+inttostr(AcceptNum)+个连接;endelseifEvent=FD_CLOSEthenbeginWSAAsyncSelect(AcceptSockindex,FormTCPUDP.Handle,0,0);ifindex0thenbeginfori:=0toCmbSendto.Items.Count-1doifCmbSendto.Items.Stringsi=套接口:+inttostr(index)+地址:+inet_ntoa(FSockAcceptindex.sin_addr)+端口:+inttostr(ntohs(FSockAcceptindex.sin_port)thenbeginCmbSendto.Items.Delete(i);break;end;CloseSocket(AcceptSockindex);AcceptSockFlagindex:=false;AcceptNum:=AcceptNum-1;StatusBar1.Panels2.Text:=共有:+inttostr(AcceptNum)+个连接;end;end;end;procedureTFormTCPUDP.RBTCPClick(Sender:TObject);beginwriteiniBool(INIPath+TCPUDP.ini,Setting,TCPStatus,true);RBServer.Enabled:=true;RBClient.Enabled:=true;ifRBServer.CheckedthenbeginPanelDest.Visible:=false;CmbSendto.Enabled:=true;endelsebeginPanelDest.Visible:=true;PanelLocal.Visible:=false;end;ChkBind.Enabled:=false;TcpFlag:=true;end;procedureTFormTCPUDP.RBUDPClick(Sender:TObject);beginwriteiniBool(INIPath+TCPUDP.ini,Setting,TCPStatus,false);RBServer.Enabled:=false;RBClient.Enabled:=false;PanelDest.Visible:=true;TcpFlag:=false;ChkBind.Enabled:=true;CmbSendto.Enabled:=false;PanelLocal.Visible:=true;end;procedureTFormTCPUDP.BtnCloseClick(Sender:TObject);vari:integer;beginWinSockClose();BtnConnect.Enabled:=true;BtnClose.Enabled:=false;BtnSend.Enabled:=false;CmbSendto.Clear;fori:=0toStatusBar1.Panels.count-1doStatusBar1.Panelsi.Text:=;Statusbar1.Panels0.Text:=已关闭套接字!;end;procedureTFormTCPUDP.FormClose(Sender:TObject;varAction:TCloseAction);beginifBtnClose.EnabledthenWinSockClose();end;procedureTFormTCPUDP.RBClientClick(Sender:TObject);beginwriteiniBool(INIPath+TCPUDP.ini,Setting,ServerStatus,false);ServerFlag:=false;PanelDest.Visible:=true;CmbSendto.Enabled:=false;ifTcpflagthenPanelLocal.Visible:=falseelsePanelLocal.Visible:=true;end;procedureTFormTCPUDP.RBServerClick(Sender:TObject);beginwriteiniBool(INIPath+TCPUDP.ini,Setting,ServerStatus,true);ServerFlag:=true;ifTcpflagthenbeginPanelDest.Visible:=false;CmbSendto.Enabled:=true;ChkBind.Enabled:=fal

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论