http://pmaboy.blog.sohu.com/84693130.html
Tcpserver组件属性
LocalHostAddr 获取本地机IP;
localport 获取本地端口;
LocalHostName 本地计算机名称;
BlockMode属性,可以设定TTCPServer为bmBlockingmNonBlockingmThreadBlocking这三种通讯模式;
bmBlocking 为阻塞模式,以同步的方式进行数据传输,
bmNonBlocking 非阻塞模式,以异步的方式进行数据传输,
bmThreadBlocking 线程异步模式,创建一个子线程与TcpClient进行通讯,在线程中以同步的方式传输数 据;
如果是bmBlocking模式,可以OnAccept事件中编写代码
procedure TForm1.TcpServer1Accept(Sender: TObject; ClientSocket: TCustomIpClient);
//接收tcpclient的数据
ClientSocket.ReceiveFrom()
ClientSocket.ReceiveBuf()
//向tcpclient发送数据
ClientSocket.SendBuf()
ClientSocket.SendTo()
如果是bmThreadBlocking模式,可以OnGetThread事件中编写代码
procedure TForm1.TcpServer1GetThread(Sender: TObject; var ClientSocketThread: TClientSocketThread);
begin
ClientSocketThread.ClientSocket.
//接收tcpclient的数据
ClientSocketThread.ClientSocket.ReceiveFrom()
ClientSocketThread.ClientSocket.ReceiveBuf()
//向tcpclient发送数据
ClientSocketThread.ClientSocket.SendBuf()
ClientSocketThread.ClientSocket.SendTo()
Listening 返回布尔值,是否正在侦听
LookupHostName 指定参数IP可以获取其主机名;
D7-->TCPserver通信方法
1、指定其Localport属性为大于1024值的整型值,目的是指定TCPsever1的监听端口;
2、设定其通信方式:Blockmode;
3、打开TCPsever1监听客户端连接请求,TCPsever1.active:=true;
4、在TCPserver1.OnAccept事件中写读写客户端代码;Receivebuf(char数组,长度),Sendbuf(char数组,长度)读写客户端连接;
var buff:array[0..255]of char;
tmpbuf:string;
begin
Clientsocket.OnReceive:=onbuff;//自定义Onbuff显示接收到数据
while ClientSocket.Connected do
begin
if ClientSocket.WaitForData(50)then//保证无阻塞的读数据;
ClientSocket.receivebuf(buff[0],sizeof(buff)); //必须有这外判定不然发不出数据
if outbuf<>'' then //outbuf为全局变量用于接收Form中的Memo值;
begin
tmpbuf:=outbuf;
outbuf:='';
ClientSocket.SendBuf(pchar(tmpbuf)^,length(tmpbuf));
end;
//将接收到的数据显示到Memo
procedure Tform1.onbuff(Sender: TObject; Buf: pchar; var DataLen: Integer);
var buff:pchar;
st:string;
I:integer;
begin
st:='';
buff:=buf;
for i:=0 to datalen do
begin
st:=st+ buff^;
inc(buff);
end;
self.memo1.Lines.Add(st) ;
end;