68_用Delphi编写局域网中的TCP聊天程序
用Delphi编写局域网中的UDP聊天程序

用Delphi编写局域网中的UDP聊天程序Internet盛行的今天,网上聊天已成为一种时尚。
同时,各单位已建成了自己的局域网;能否在局域网上实现聊天呢?可以,网上到处都有这种工具。
当然,我们可以拥有自己版权的聊天工具。
User Datagram Protocol (UDP)协议,是一种无连接协议。
在Delphi中利用这种协议,可以轻松的编写出聊天程序,以下的程序,在Delphi 5+Pwin98中通过。
打开Delphi,新建Application放置以下几个控件:Panel1、Panel2,其属性如下:然后,放置以下控件:Edit1ListBox1Memo1Button1Button2BitBtn1Nmudp1其主要控件的属性如下:各主要控件的功能如下:现在的界面如下:源程序如下:unit main;interfaceusesWindows,messages,SysUtils,Classes,Graphics,Controls,Forms,Dialogs,StdCtrls,Buttons,ExtCtrls,NMUDP,Menus,ComCtrls,Win Sock; file://增加WinSocktypeTForm1 = class(TForm)NMUDP1: TNMUDP;Panel1: TPanel;Panel2: TPanel;Label1: TLabel;Edit1: TEdit;BitBtn1: TBitBtn;Memo1: TMemo;Panel3: TPanel;Panel4: TPanel;ListBox1: TListBox;Button1: TButton;Button2: TButton;procedure FormShow(Sender: TObject);procedure BitBtn1Click(Sender: TObject);procedure NMUDP1DataReceived(Sender: TComponent; NumberBytes: Integer;FromIP: String; Port: Integer);procedure Edit1KeyPress(Sender: TObject; var Key: Char);procedure Button1Click(Sender: TObject);procedure Button2Click(Sender: TObject);private{ Private declarations }public{ Public declarations }end;varForm1: TForm1;ComputerName: array[0..127] of Char;implementation{$R *.DFM}procedure TForm1.FormShow(Sender: TObject);varsz: dword;beginsz := SizeOf(Computername);GetComputerName(ComputerNamesz);//得到本机的标识ListBox1.Items.Clear;ListBox1.Items.Add(’大家’);//在网友清单中,增加”大家”和ListBox1.Items.Add(ComputerName);//本机名称ListBox1.ItemIndex:=0;end;procedure TForm1.BitBtn1Click(Sender: TObject);varMyStream: TMemoryStream;TmpStr: String;i:integer;Beginif Edit1.Text<>’’ then file://如果所说的内容不为空则发送。
delphisocket发送和接受tcp信息包

delphisocket发送和接受tcp信息包展开全文最近有个项目用到delphi 以前学过但是网络通讯这块不懂以前是直接接受字符串现在改用传递信息包希望大侠帮忙写下接受和发送特定信息包的代码下面为信息包的格式和内容数据包格式如下图所示,所包含的内容从左到右进行传输:包头中的信息全部为网络字节顺序!包头信息中,开始标识(head),版本信息(version)为固定格式;包体长度(length),提示整个包体(包括包头)的长度,接收方据此来完成一个业务数据包的接收和解析;命令号(command),为客户端和服务器约定的业务命令,从0到65535,具体定义详见下表:应答状态(status),请求时总设置为0;应答时,由SP应用服务程序返回相应的操作结果或错误原因;任务流水号(taskid)由自行定义,SP应用程序在响应包中必须返回,SP应用程序可以将此作为数据包一段时间内的唯一序列号。
发送方标识1(sender)、发送方标识2(sessionid)、时间戳(timestamp)以及保留字段(reserved),可以为发送方保留一些私有信息,返回包时原样返回。
包头信息中,除了包体长度(length)以外,其他的字段,包括开始标识(head),版本信息(version),任务流水号(taskid),发送方标识1(sender),发送方标识2(sessionid),时间戳(timestamp),以及数据加密标识(flag),需要在响应包中原样返回;流程1、通用网关在连接建立之后,根据刚才加密的字节流,加上信息包头,组合成信息包,然后发送(Send)信息包,发送的字节数为加密后的字节流字节数+24(24信息包头的字节长度);在上述的例子中,信息包大约如ffff0200 00001100 00004e5f 00114b3f 00000000 0100 0038 2fd65329e2770074791503c2dab1d209fe0225636dd07f7277bd2 91209e1a498df28f7af2f0eb4f1be2831f0fa8987b7f9;其中业务加密字节流的长度这里是56,体现在网络字节中是0x0038,如果是x86系列的PC,需要做主机到网络(ntohs)字节顺序转换;2、 SP应用服务程序接收(Recv)该信息包,根据包头信息截取对应的字节流,然后进行解密处理,得到加密前的业务字符串,另外还需要把其他的包头标识、两个包头保留字,存储在本地;3、SP应用服务程序根据流程开发人员与之协商好的格式对接收的字符串进行解析,然后进行响应的处理4、SP应用服务程序在发送之前,同样根据密匙对该返回字符串进行加密处理,然后对加密字节流长度进行计算,加上刚才发送过来的包头标识和版本号以及保留字等,组合成信息包;注意这时,字节流的长度是返回加密字节流的长度,而且是网络字节的以下是自己接受字符串的时的代码procedure TForm1.ServerSocketClientRead(Sender: TObject;Socket: TCustomWinSocket);varlmsg:String;vflag,i,j:Integer;larriveDate:TarriveDate;ip:String;islimit:Boolean;resData:String;//返回数据buff:array[0..255]of byte;beginip:=Socket.RemoteAddress;islimit:=True;For j:=0 to ips.Count-1 DoBeginif (ip=ips[j]) thenbeginislimit:=False;end;End;if not islimit thenBeginCoInitialize(nil);Socket.ReceiveBuf(buff,4);//应该就在这里修改吧lmsg:=Socket.ReceiveText;SendTo();Memo1.Lines.Add(DateTimeTostr(now)+'来自主机'+ip+'的请求数据:'+lmsg );saveToLog(DateTimeTostr(now)+'来自主机'+ip+ ' 的请求数据:'+ lmsg);if lmsg<>'' thenBegintrysaveToLog(DateTimeTostr(now)+'开始处理接受数据'+lmsg);larriveDate:=analyecmdData(lmsg);vflag:=exChange(larriveDate);Memo1.Lines.Add('*'+Socket.ReceiveText+'*'+lmsg);Memo1.Lines.Add(DateTimeTostr(now)+'数据处理完毕:处理结果:'+inttostr(vflag));saveToLog(DateTimeTostr(now)+'数据处理完毕:处理结果:'+inttostr(vflag));exceptbeginvflag:=1;Memo1.Lines.Add(DateTimeTostr(now)+'数据处理异常:'+inttostr(vflag));saveToLog(DateTimeTostr(now)+'数据处理异常:'+inttostr(vflag));end;//vflag:=1;end;for i:=0 to sessions dobegin //取得匹配的客户端if session[i].CHandle = Socket.SocketHandle thenbegincase vflag of0: resData:=inttostr(vflag)+'$'+erID+'$'+larriv eDate.TelNo+'$'+inttostr(larriveDate.inPutKey);1: resData:='1'+'$'+'系统繁忙请稍后冲值';2: resData:='2'+'$'+'平台用户ID不存在';end;session[i].CSocket.SendText(resData);Memo1.Lines.Add(DatetimeT ostr(now)+'向客户端发送处理完毕命令'+resData);saveToLog(DatetimeTostr(now)+'向客户端发送处理完毕命令'+resData);end;end;end;CoUninitialize;endelseBeginCoInitialize(nil);CoUninitialize;// saveToLog(DatetimeTostr(now)+'非法访问Ip'+ip+'访问被阻止');End;end;。
用DELPHI编写网络聊天程序

用DELPHI编写网络聊天程序
田文雅
【期刊名称】《计算机时代》
【年(卷),期】2001(000)009
【摘要】@@ 1引言rnDelphi是一种面向对象的可视化应用程序开发工
具.Delphi 5.0中包含了一组Internet组件,用于创建Client/Server应用程序,实现基于Windows Socket(简称WinSock)的编程,访问HTTP、UDP、FTP、SMTP、POP3和NNTP等服务.
【总页数】2页(P31-32)
【作者】田文雅
【作者单位】浙江经贸职业技术学院,310012
【正文语种】中文
【相关文献】
1.网络通信程序制作实例--简单网络聊天程序制作 [J], 尹汪宏
2.第2章 Delphi网络与通信编程实例——例题11 利用Delphi实现通用多线程网络端口扫描器 [J], 王波
3.第5章 Java网络与通信编程实例——例题46 利用Java语言编写多线程聊天程序 [J], 甘剑;骆衍
4.Delphi环境下基于UDP的聊天程序 [J], 罗定福;熊传玉;徐尤华
5.Delphi环境下基于UDP的聊天程序 [J], 罗定福;熊传玉;徐尤华
因版权原因,仅展示原文概要,查看原文内容请购买。
delphi网络编程

delphi网络编程掌握网络编程的基本原理掌握网络控制的使用方法具备通过使用网络控制开发简单网络应用程序的能力Delphi 的Socket 编程概述Socket 是建立在传输层协议(主要是TCP 和UDP)上的一种套接字规范,它定义两台计算机间进行通信的规范(即一种编程规范),如果说两台计算机是利用一个“通道”进行通信,那么这个“通道”的两端就是两个套接字。
套接字屏蔽了底层通信软件和具体操作系统的差异,使得任何两台安装了TCP 协议软件和实现了套接字规范的计算机之间的通信成为可能。
在Delphi 中,其底层的Socket 也应该是Windows的Socket。
Socket减轻了编写计算机间通信软件的难度。
Inprise在Delphi中对Windows Socket进行了有效的封装,使用户可以很方便地编写网络通信程序。
TCP/IP 协议及特点1. TCP/IP体系结构TCP/IP 协议实际上就是在物理网上的一组完整的网络协议。
其中TCP 是提供传输层服务,而IP 则是提供网络层服务。
TCP/IP协议簇(如图1所示)包括协议如下。
(1) IP:网间协议(Internet Protocol)。
此协议负责主机间数据的路由和网络上数据的存储。
同时为ICMP,TCP,UDP提供分组发送服务,用户进程通常不需要涉及这一层。
(2) ARP:地址解析协议(Address Resolution Protocol)。
此协议将网络地址映射到硬件地址。
(3) RARP:反向地址解析协议(Reverse Address Resolution Protocol)。
此协议将硬件地址映射到网络地址(4) ICMP:网间报文控制协议(Internet Control Message Protocol)。
此协议处理信关和主机的差错和传送控制。
(5) TCP:传送控制协议(Transmission Control Protocol)。
delphi一个用socket封装UDPTCP通信的例子

unit UnitTCPUDP;interfaceusesWindows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,Dialogs, StdCtrls,WinSock, ExtCtrls, ComCtrls,inif iles,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: TStatic Text;STCommand: TStatic Text;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;procedure BtnSendClick(Sender: TObject);procedure BtnConnectClick(Sender: TObject);procedure RBTCPClick(Sender: TObject);procedure RBUDPClick(Sender: TObject);procedure BtnCloseClick(Sender: TObject);procedure FormClose(Sender: TObject; var Action: TCloseAction);procedure RBClientClick(Sender: TObject);procedure RBServerClick(Sender: TObject);procedure ChkBindClick(Sender: TObject);procedure FormCreate(Sender: TObject);procedure EditHostPortChange(Sender: TObject);procedure EditRemoteHostChange(Sender: TObject);procedure EditRemotePortChange(Sender: TObject);procedure FormActivate(Sender: TObject);procedure CmbSendToKeyPress(Sender: TObject; var Key: Char); {消息接送}private{ Private declarations }FirstFlag:Boolean;INIPath:String;procedure R eadData(var Message: TMessage);function ReadTCPUDPIni():boolean; //读取配置信息procedure Wri t eIniStr(FileName:String;section:string;Ident:string;StringValue:string);//写系统信息 procedure Wri t eIniBool(FileName:String;section:string;Ident:string;BoolValue:Boolean);//写系统信息 protected{ Protected declarations }{ other fields and methods}procedure wndproc(var message:Tmessage);override;public{ Public declarations }end;constDATA_LENGTH =120; //数据长度typeTUDPaction = packed recordopcode:byte; //操作码index:word; //序列号Command:byte; //命令字data:array[0..(DATA_LENGTH-1)] of char; //数据end;varFormTCPUDP: TFormTCPUDP;AcceptSock:Array[0..MAX_ACCEPT] OF Tsocket;FSockAccept : Array[0..MAX_ACCEPT] OF TSockAddrIn;AcceptSockFlag: Array[0..MAX_ACCEPT] OF boolean;AcceptNum:integer=0;FSockLocal : TSockAddrIn;PackageID:integer=0; //包序号BindFlag:Boolean=true;TcpFlag:Boolean=false;ServerFlag:Boolean=false;function WinSockInital(Handle: HWnd):bool;Procedure WinSockClose();implementation{$R *.dfm}{始化SOCKET}function WinSockInital(Handle: HWnd):bool;var TempWSAData: TWSAData;i:integer;beginresult := false;{ 1 初始化SOCKET}if WSAStartup(2, TempWSAData)=1 then //2表示启用winsock2 exi t;{若是用UDP通信,则用}if TcpFlag thenAcceptSock[0]:=Socket(AF_INET,SOCK_STREAM,0)elseAcceptSock[0]:=Socket(AF_INET,SOCK_DGRAM,0);if AcceptSock[0]=SOCKET_ERROR thenexi t;if (BindFlag and not tcpflag) or (Serverflag and tcpflag) thenif bind(AcceptSock[0],FSockLocal,sizeof(FSockLocal))<>0 then beginWinSockClose();exit;end;if Tcpflag thenif Serverflag thenbeginif Listen(AcceptSock[0],1)<>0 then //等待连接队列的最大长度为1begin WinSockClose();exi t;end;endelseif connect(AcceptSock[0],FSockAccept[0],sizeof(FSockAccept[0]))<>0 thenbeginWinSockClose();exi t;end;{FD_READ 在读就绪的时候, 产生WM_SOCK 自定义消息号}if not TcpFlag thenWSAAsyncSelect(AcceptSock[0], Handle , WM_SOCK, FD_READ)else if Serverflag thenWSAAsyncSelect(AcceptSock[0], Handle , WM_SOCK, FD_READ or FD_ACCEPT or FD_CLOSE) elseWSAAsyncSelect(AcceptSock[0], Handle , WM_SOCK, FD_READ or FD_CLOSE);R esult:=true;end;{关闭SOCKET}Procedure WinSockClose();var i:integer;beginfor i:=1 to MAX_ACCEPT DOif AcceptSockFlag[i] thenbeginCloseSocket(AcceptSock[i]);AcceptSockFlag[i]:=false;end;CloseSocket(AcceptSock[0]); {closesocket函数用来关闭一个描述符为AcceptSock[0]套接字}WSACleanup;end;function TFormTCPUDP.ReadTCPUDPIni():boolean;var ti:TiniFile;beginti:=TIniFile.Create(INIPath+'TCPUDP.ini');EditHostPort.text:=ti.ReadString('Setting','LocalPort','');ChkBind.Checked:=ti.ReadBool('Setting','BindStatus',false);EditR emotePort.text:=ti.ReadString('Setting','RemotePort','');EditR emoteHost.text:=ti.ReadString('Setting','R emoteHost','');RBTCP.Checked:=ti.ReadBool('Setting','TCPStatus',false);RBUDP.Checked:=not RBTCP.Checked;RBServer.Checked:=ti.R eadBool('Setting','ServerStatus',false);RBClient.Checked:=not RBServer.Checked;end;procedure TFormTCPUDP.WriteIniStr(FileName:String;Section:string;Ident:string;StringValue:string); var ti:TiniFile;beginti:=TIniFile.Create(FileName);ti.writestring(section,Ident,StringValue);ti.Free;end;procedure TFormTCPUDP.WriteIniBool(FileName:String;Section:string;Ident:string;BoolValue:Boolean); var ti:TiniFile;beginti:=TIniFile.Create(FileName);ti.writebool(section,Ident,BoolValue);ti.Free;end;procedure TFormTCPUDP.BtnSendClick(Sender: TObject);var SEND_PACKAGE : TUDPaction; //数据发送i:integer;s:String;beginFillchar(SEND_PACKAGE.data,Data_Length,chr(0));SEND_PACKAGE.data[0]:='1';SEND_PACKAGE.data[1]:='2';SEND_PACKAGE.data[2]:='3';SEND_PACKAGE.opcode:=2;SEND_PACKAGE.index:=PackageID;SEND_mand:=3;s:=editsend.Text;for i:=0 to length(EditSend.Text)-1 doSEND_PACKAGE.data[i]:=s[i+1];PackageID:=PackageID+1;if not (Tcpflag and Serverflag) thensendto(AcceptSock[0], SEND_PACKAGE,sizeof(SEND_PACKAGE), 0, FSockAccept[0], sizeof(FSockAcce pt[0]))else if AcceptNum=0 thenApplication.MessageBox('没有一个客户端和您建立连接','信息提示',MB_OK)elsebegini:=pos(' ',CmbSendto.Text);if i>0 thenbegini:=strtoint(MidStr(CmbSendTo.Text,8,i-8));sendto(AcceptSock[i], SEND_PACKAGE,sizeof(SEND_PACKAGE), 0, FSockAccept[i], sizeof(FSockAcce pt[i]));endelseApplication.MessageBox('您没有选择发送方','错误提示',MB_OK);end;// sendto(AcceptSock[0], NbtstatPacket,50, 0, FSockAccept[0], sizeof(FSockAccept[0]));end;procedure TFormTCPUDP.BtnConnectClick(Sender: TObject);var s:String;i:integer;begins:='正在建立连接....';StatusBar1.Panels[0].Text:=s;Application.ProcessMessages;FSockLocal.sin_family:=AF_INET;FSockLocal.sin_port:=htons(strtoint(Edi t Hostport.Text));FSockAccept[0].sin_family:=AF_INET;FSockAccept[0].sin_port:=htons(strtoint(EditRemoteport.Text));FSockAccept[0].SIn_Addr.S_addr := inet_addr(PChar(EditR emoteHost.Text));//inet_addr(pchar(IP)); if WinSockInital(FormTCPUDP.Handle) thenbeginBtnConnect.Enabled:=false;BtnClose.Enabled:=true;BtnSend.Enabled:=true;s:='连接成功!';if ChkBind.Checked thens:=s+', ---绑定端口';if RBTcp.Checked thenbegins:=s+',---TCP方式';if RBServer.Checked thens:=s+',---服务端'elses:=s+',---客户端';endelses:=s+',---UDP方式';if tcpflag and Serverflag thenbeginAcceptNum:=0;CmbSendto.Clear;StatusBar1.Panels[2].Text:='共有:'+inttostr(AcceptNum)+'个连接';end;endelsebeginfor i:=0 to StatusBar1.Panels.count-1 doStatusBar1.Panels[i].Text:='';s:='创建套接字失败!!';end;StatusBar1.Panels[0].Text:=s;end;procedure TFormTCPUDP.wndproc(var Message: TMessage);beginif (Message.Msg>=WM_SOCK) and (Message.Msg<=WM_SOCK+MAX_ACCEPT) thenReadData(Message)elseinherited wndproc(message);end;procedure TFormTCPUDP.ReadData(var Message: TMessage);varReceive_PACKAGE : TUDPaction; //数据发送flen,len,i,index: integer;Event: word;beginIndex:=(Message.Msg-WM_SOCK);flen:=sizeof(FSockAccept[Index]);Event := WSAGetSelectEvent(Message.LParam);if Event = FD_READ thenbeginlen := recvfrom(AcceptSock[Index], Receive_PACKAGE, sizeof(R eceive_PACKAGE), 0, FSockAccept[In dex], Flen);if len> 0 thenbeginStatusBar1.Panels[0].Text:='收到来自ip地址:'+inet_ntoa(FSockAccept[Index].sin_addr)+' 端口:'+inttostr(ntohs(FSockAccept[Index].sin_port))+'的数据';StOpCode.Caption:= format('%.2d',[Receive_PACKAGE.opCode]);StIndex.Caption:= format('%d',[Receive_PACKAGE.Index]);StCommand.Caption:= format('%.2d',[R eceive_mand]);MemoR eceive.Lines.Add(StrPas(Receive_PACKAGE.data))end;endelse if Event=FD_ACCEPT thenbeginfor i:=1 to MAX_ACCEPT DOif not AcceptSockFlag[i] thenbeginflen:=Sizeof(FSockAccept[i]);AcceptSock[i]:=accept(AcceptSock[0],@FSockAccept[i],@flen);WSAAsyncSelect(AcceptSock[i], Handle , WM_SOCK+i, FD_READ or FD_CLOSE);AcceptSockFlag[i]:=true;AcceptNum:=AcceptNum+1;CmbSendto.I tems.Add('套接口:'+inttostr(i)+' 地址:'+inet_ntoa(FSockAccept[i].sin_addr)+' 端口:'+inttostr(ntohs(FSockAccept[i].sin_port)));break;end;StatusBar1.Panels[2].Text:='共有:'+inttostr(AcceptNum)+'个连接';endelse if Event=FD_CLOSE thenbeginWSAAsyncSelect(AcceptSock[index], FormTCPUDP.Handle, 0, 0);if index<>0 thenbeginfor i:=0 to CmbSendto.I tems.Count-1 doif CmbSendto.I tems.Strings[i]= '套接口:'+inttostr(index)+' 地址:'+inet_ntoa(FSockAccept[index].sin_addr)+' 端口:'+inttostr(ntohs(FSockAccept[index].sin_port)) thenbeginCmbSendto.Items.Delete(i);break;end;CloseSocket(AcceptSock[index]);AcceptSockFlag[index]:=false;AcceptNum:=AcceptNum-1;StatusBar1.Panels[2].Text:='共有:'+inttostr(AcceptNum)+'个连接';end;end;end;procedure TFormTCPUDP.RBTCPClick(Sender: TObject);beginwriteiniBool(INIPath+'TCPUDP.ini','Setting','TCPStatus',true);RBServer.Enabled:=true;RBClient.Enabled:=true;if RBServer.Checked thenbeginPanelDest.Visible:=false;CmbSendto.Enabled:=true;endelsebeginPanelDest.Visible:=true;PanelLocal.Visible:=false;end;ChkBind.Enabled:=false;TcpFlag:=true;end;procedure TFormTCPUDP.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;procedure TFormTCPUDP.BtnCloseClick(Sender: TObject);var i:integer;beginWinSockClose();BtnConnect.Enabled:=true;BtnClose.Enabled:=false;BtnSend.Enabled:=false;CmbSendto.Clear;for i:=0 to StatusBar1.Panels.count-1 doStatusBar1.Panels[i].Text:='';Statusbar1.Panels[0].Text:='已关闭套接字!!';end;procedure TFormTCPUDP.FormClose(Sender: TObject; var Action: TCloseAction); beginif BtnClose.Enabled then WinSockClose();end;procedure TFormTCPUDP.RBClientClick(Sender: TObject);beginwriteiniBool(INIPath+'TCPUDP.ini','Setting','ServerStatus',false);ServerFlag:=false;PanelDest.Visible:=true;CmbSendto.Enabled:=false;if Tcpflag thenPanelLocal.Visible:=falseelsePanelLocal.Visible:=true;end;procedure TFormTCPUDP.RBServerClick(Sender: TObject);beginwriteiniBool(INIPath+'TCPUDP.ini','Setting','ServerStatus',true);ServerFlag:=true;if Tcpflag thenbeginPanelDest.Visible:=false;CmbSendto.Enabled:=true;ChkBind.Enabled:=false;ChkBind.Checked:=true;endelseChkBind.Enabled:=true;PanelLocal.Visible:=true;end;procedure TFormTCPUDP.ChkBindClick(Sender: TObject);beginwriteiniBool(INIPath+'TCPUDP.ini','Setting','BindStatus',ChkBind.Checked); BindFlag:=ChkBind.Checked;end;procedure TFormTCPUDP.FormCreate(Sender: TObject);var i:integer;beginFirstFlag:=true;for i:=1 to MAX_ACCEPT doAcceptSockFlag[i]:=false;INIPath:=extractFilePath(ParamStr(0));end;procedure TFormTCPUDP.EditHostPortChange(Sender: TObject);beginwriteiniStr(INIPath+'TCPUDP.ini','Setting','LocalPort',EditHostPort.Text);end;procedure TFormTCPUDP.EditRemoteHostChange(Sender: TObject);beginwriteiniStr(INIPath+'TCPUDP.ini','Setting','RemoteHost',EditR emoteHost.Text); end;procedure TFormTCPUDP.EditRemotePortChange(Sender: TObject);beginwriteiniStr(INIPath+'TCPUDP.ini','Setting','RemotePort',EditRemotePort.Text); end;procedure TFormTCPUDP.FormActivate(Sender: TObject);beginif FirstFlag thenbeginFirstFlag:=false;ReadTCPUDPIni();end;end;procedure TFormTCPUDP.CmbSendToKeyPress(Sender: TObject; var Key: Char); beginkey:=chr(0);end;end.。
利用Delphi编写Socket通信程序

利用Delphi编写Socket通信程序一、前言随着计算机技术的不断发展,网络应用得到了越来越广泛的应用,而Socket编程作为网络编程中最基础、最重要的部分,具有非常重要的意义。
Delphi是一种构建Windows应用程序的高级集成开发工具,支持对象化设计、事件驱动、可视化编程等多种编程方式。
Delphi具有非常强大的GUI设计、数据访问、组件开发等特点,可以方便地应用到Socket编程中,实现Socket通信程序的开发。
本文就介绍利用Delphi编写Socket通信程序相关的知识。
二、Socket编程基础Socket是一种用于网络通信的编程接口,它把网络通信抽象成发送和接收数据的过程。
Socket编程分为客户端和服务器两部分,客户端负责向服务器发起连接请求,服务器则负责接收客户端的连接请求,并根据请求提供相应的服务。
Socket编程中,通常使用TCP/IP协议进行数据传输。
TCP协议是一种可靠的、面向连接的协议,它通过三次握手建立连接,保证数据的可靠性、完整性和顺序性。
而UDP协议则是一种不可靠的、无连接的协议,它不保证数据的可靠性和完整性,但具有数据传递速度快等特点。
通常,TCP协议适用于对数据可靠性要求较高的应用场景,如文件传输、邮件系统、即时通信等;而UDP协议适用于对数据传输速度要求较高的应用场景,如视频直播、网络游戏等。
三、利用Delphi编写Socket通信程序1. 创建Socket使用Delphi进行Socket编程,可通过TServerSocket和TClientSocket组件来实现。
TServerSocket组件用于创建服务器Socket,TClientSocket组件用于创建客户端Socket。
在Delphi中,可以通过在组件面板中拖拽TServerSocket或TClientSocket组件来创建Socket。
使用TServerSocket组件创建服务器Socket的示例代码如下:```delphiprocedure TMyForm.FormCreate(Sender: TObject);begin ServerSocket1.Port := 8888;ServerSocket1.Active := True;end;procedure TMyForm.ServerSocket1ClientConnect(Sender: TObject; Socket: TCustomWinSocket);beginMemo1.Lines.Add(Socket.RemoteAddress + ' connected.');end;```上述代码中,将ServerSocket1的Port属性设置为8888,表示该服务器监听8888端口的连接请求。
Delphi2004_局域网聊天程序的实现9000

局域网的聊天程序的实现摘要网络通讯是目前计算机用户进行交流最普遍的方式,各种各样的聊天软件也层出不穷;服务提供商也提供了越来越丰富的通讯服务功能。
本文介绍了在Windows环境下开发局域网聊天程序思路和方法。
系统使用流行的Delphi7.0开发软件,采用Socket技术实现网络通讯。
数据库使用Delphi自带的Database desktop。
系统采用典型的C/S(服务器/客户端)构架。
系统主要实现了用户注册、登录、聊天、服务器管理等功能。
本系统从需求分析、系统的设计、具体功能的实现都严格遵循了软件设计工程的思想。
关键词: Socket; TCP/IP; C/S目录论文总页数:22页1 引言 (2)2 局域网聊天程序系统分析......................................................................... 错误!未定义书签。
2.1 系统理论基础 .................................................................................. 错误!未定义书签。
2.1.1 TCP/IP的特点 ........................................................................ 错误!未定义书签。
2.1.2 客户机/服务器模式 ............................................................... 错误!未定义书签。
2.1.3 Socket介绍 ............................................................................. 错误!未定义书签。
2.2 系统需求分析 .................................................................................. 错误!未定义书签。
delphi tcpclient 用法

delphi tcpclient 用法As a Delphi developer, you may find yourself needing to use the TCPClient component in your projects. TCPClient is a powerful component that allows you to establish and manage TCP connections with remote servers. It provides a simple and easy-to-use interface for sending and receiving data over the network.作为一名Delphi开发人员,你可能会发现自己需要在项目中使用TCPClient组件。
TCPClient是一个强大的组件,允许你与远程服务器建立和管理TCP连接。
它提供了一个简单易用的界面,用于在网络上发送和接收数据。
When using TCPClient in Delphi, you can easily establish a connection to a remote server by setting the Host and Port properties of the component. Once the connection is established, you can use methods like SendData and ReceiveData to send and receive data over the network. It's important to handle errors and exceptions properly when working with TCPClient to ensure the stability and reliability of your application.在Delphi中使用TCPClient时,你可以通过设置组件的Host和Port属性轻松地建立与远程服务器的连接。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
用Delphi编写局域网中C/S型聊天程序中原工学院计算机教研室夏敏捷Internet盛行的今天,网上聊天QQ已成为一种时尚。
QQ是深圳腾讯公司的一个网络实时通讯软件,在国内拥有大量的用户群。
但QQ必须连接上互联网登陆到腾讯的服务器才能使用。
所以我们可以自己写一个在局部网里面使用的自己的QQ。
QQ使用的是UDP协议,这是一种无连接协议,即通信双方不用建立连接就可以发送信息,所以效率比较高。
Delphi本身自带的FastNEt公司的NMUDP控件就是一个UDP协议的用户数据报控件。
这里我们编写的局域网上实现聊天的程序采用的是TCP协议,TCP 是一种面向连接协议,具有较高的可靠性。
在Delphi中利用ClientSocket、ServerSocket这两种控件(Internet面板上),可以轻松的编写出C/S聊天程序,以下的程序在Delphi 6+winXP 中通过。
一、原理首先建立客户与主机的连接,把要发送的文字信息写进字符串中,然后ClientSocket组件的Socket..sendtext方法把文本发送出去。
当主机有数据接收时,触发它的ServerSocket 组件onClientRead事件,我们在这里用socket.ReceiveText接收字符信息,然后显示出来。
主机可以通过Socket..sendtext方法再将此用户信息转发给所有用户或单独的用户,在数据到达客户端后触发客户端OnRead事件,接受主机的数据。
为了区分不同的信息(新用户信息、昵称、交谈、用户离开)设计了以下协议格式:1.发送添加的新用户信息的格式:“添加用户”@用户的昵称^它的IP@用户的昵称^它的IP@……@此信息中将所有的用户的昵称和它的IP均包含在其中,新用户是最后一个。
2.发送昵称信息的格式:“昵称”@用户的昵称此信息用于在客户和服务器建立连接后,发送用户的昵称给服务器。
而用户的IP 地址可以通过(socket.RemoteAddress)得出。
3.发送文本对话信息的格式:“交谈”@to用户的昵称@交谈的内容4.发送离开信息的格式:“离开”@离开的用户的昵称二、客户端:新建一个工程,在Internet面板拖一个ClientSocket控件到窗口,然后依次放上一个EDIT, 一个ListBox和一个RichEdit,两个按钮,一个状态条StatusBar1。
当用户点击“连接主机”按钮时,用户输入服务器主机的IP及紧接着自己的昵称。
procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word;Shift: TShiftState); beginif key=13 then //最好加本地IPbeginif listbox1.itemindex>=0 thenbeginclientsocket1.Socket.SendText('交谈@'+'to'+listBox1.Items.strings[listbox1.itemindex]+'@ '+edit1.Text );edit1.text:='';endelseshowmessage('请选择交谈对象');end;end;procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);beginclientsocket1.Active :=false;clientsocket1.close;end;procedure TForm1.Button1Click(Sender: TObject);var str1:string;beginstr1:=inputbox('建立连接','请输入IP','127.0.0.1');if trim(str1)<>'' thenbeginclientsocket1.Port:=5555;//server portclientsocket1.host:=str1;tryclientsocket1.active:=true;str1:=inputbox('建立连接','请输入昵称','泡泡');clientsocket1.Socket.SendText('昵称@'+str1);exceptshowmessage('连接失败');end;end;end;procedure TForm1.Button2Click(Sender: TObject);beginclose;end;procedure TForm1.ClientSocket1Connect(Sender: TObject;Socket: TCustomWinSocket); beginStatusBar1.SimpleText:='连接成功';end;procedure TForm1.ClientSocket1Read(Sender: TObject; Socket: TCustomWinSocket);var str1,name,str2,nei_rong:string;n,i:integer;beginstr1:=socket.ReceiveText;str2:=copy(str1,1,pos('@',str1)-1);if str2='添加用户' thenbeginlistbox1.Clear;//清除已有名单str1:=copy(str1,pos('@',str1)+1,length(str1)-pos('@',str1));while str1<>'' do //建立新名单beginname:=copy(str1,1,pos('@',str1)-1);//昵称^IPlistbox1.Items.Add(copy(name,1,pos('^',name)-1));str1:=copy(str1,pos('@',str1)+1,length(str1)-pos('@',str1));end;RichEdit1.Lines.Add(name+'进入了');end;if str2='交谈' then //交谈@xmj@hellobeginstr2:=copy(str1,pos('@',str1)+1,length(str1)-pos('@',str1));name:=copy(str2,1,pos('@',str2)-1);nei_rong:=copy(str2,pos('@',str2)+1,length(str2)-pos('@',str2));RichEdit1.Lines.Add(name+'对你说'+nei_rong);end;if str2='离开' thenbeginn:= pos('@',str1);name:=copy(str1,n+1,length(str1)-n);for i:=0 to listbox1.items.count-1 dobeginif listbox1.items.strings[i]=name thenlistbox1.items.delete(i);end;end;end;end.三、服务器端:新建一个工程,在Internet面板拖一个ServerSocket控件到窗口,然后依次放上一个EDIT, 一个ListView(ViewStyle属性为vsReport,表格型)和一个RichEdit,一个状态条StatusBar1。
procedure TForm1.FormCreate(Sender: TObject);beginserversocket1.Active :=true;RichEdit1.Lines.add(datetostr(date)+' '+timetostr(time)+'==>'+'聊天室服务器启动了');StatusBar1.SimpleText:='聊天室服务器启动了';end;procedure TForm1.ServerSocket1ClientRead(Sender: TObject;Socket: TCustomWinSocket);var s,str,name,nei_rong:string;i,n:integer;all_name,ni_cheng:string;newitem:TListItem;begins:=Socket.ReceiveText; //接收字符串n:=pos('@',s);if n>0 thenbeginstr:=copy(s,1,n-1);if str='交谈' then //格式:"交谈"@"to昵称"@"内容"beginstr:=copy(s,n+1,length(s)-n);name:=copy(str,3,pos('@',str)-3); //交谈的对象昵称nei_rong:=copy(str,pos('@',str)+1,length(str)-pos('@',str));//交谈的内容for i:=0 to ListView1.Items.count-1 do //根据发言者IP找发言者昵称beginif socket.RemoteAddress=ListView1.Items[i].subitems[0] thenbeginni_cheng:= ListView1.Items[i].caption;RichEdit1.Lines.add(ni_cheng+'对'+name+'说'+nei_rong); end;end;for i:=0 to ListView1.Items.count-1 do //根据交谈的对象昵称找交谈的对象IPbeginif name=ListView1.Items[i].caption thenname:=ListView1.Items[i].subitems[0]; //subitems[0]存放IPend;for i:=0 to ListView1.Items.count-1 do //实现私聊beginif ServerSocket1.Socket.Connections[i].RemoteAddress=name thenServerSocket1.Socket.Connections[i].SendText('交谈@'+ni_cheng+'@'+nei_rong);end;end;if str='昵称' then //昵称@xmjbeginall_name:='';newitem:=ListView1.Items.insert(ListView1.Items.count);newitem.caption:=copy(s,pos('@',s)+1,length(s)-pos('@',s));newitem.SubItems.Add(socket.RemoteAddress);newitem.SubItems.Add(socket.RemoteHost);RichEdit1.Lines.add(newitem.caption+'进来了');for i:=0 to ListView1.Items.count-1 doall_name:=all_name+ListView1.Items[i].Caption+'^'+ListView1.Items[i].subitems[0]+'@';for i:=0 to ListView1.Items.count-1 do //广播新进入用户beginServerSocket1.Socket.Connections[i].SendText('添加用户@'+all_name);end;end;end;end;procedure TForm1.ServerSocket1ClientDisconnect(Sender: TObject; Socket: TCustomWinSocket); //用户离开触发var i,j,k:integer;ni_cheng:string;beginfor i:=0 to ListView1.Items.count-1 do //ListView1中查找离开用户beginif socket.RemoteAddress=ListView1.Items[i].subitems[0] thenbeginni_cheng:= ListView1.Items[i].caption; //根据发言者IP找发言者昵称RichEdit1.Lines.add(ni_cheng+'离开了');Listview1.Items.Item[i].Delete(); break;end;end;for j:=0 to ListView1.items.count-1 do //广播离开用户ServerSocket1.Socket.Connections[j].SendText('离开@'+ ni_cheng);end;procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var i:integer;beginif key=13 thenbeginfor i:=0 to ListView1.items.count-1 do //广播用户beginServerSocket1.Socket.Connections[i].SendText('交谈@'+'all'+'@'+edit1.Text );edit1.text:='';end;end;end;end.如果读者对此感兴趣,可以到“Delphi盒子”此网站下载“C/S型聊天室3.0版”源程序网址为/article.asp?articleid=699 。