[Indy10例子]

本文作者 木桩

摘自 大富翁论坛

原地址:http://www.delphibbs.com/keylife/iblog_show.asp?xid=25008

 

网上都找不到 Indy10 TCP/UDP的例子,于是自己写了一个.
(ps:之前的标题有点误导人,想用UDP发送流,可不是这几行代码能搞定的)
先来个TCP的:

放两个TMemo,分别叫:Memo_Input, Memo_out 一个输入,一个输出
IdTCPServer1的Bindings里,设置 0.0.0.0:3999,Actibve
IdTCPClient1的Port设3999

发送按钮的代码:
var
  bufSend: TMemoryStream;
begin
  try
    //连接
    IdTCPClient1.Connect(Edit_IP.Text);
  except
    Memo_out.Lines.Add(Edit_IP.Text+' 连接超时!'); Exit;
  end;

  //准备发送
  bufSend:=TMemoryStream.Create;
  try
    Memo_Input.Lines.SaveToStream(bufSend);
    IdTCPClient1.IOHandler.Write(bufSend);   //发送流
  finally
    IdTCPClient1.Disconnect;   //关闭连接
    bufSend.Free;
  end;
end;

服务器IdTCPServer1的OnExecute事件:
//注意要uses IdContext
procedure TForm1.IdTCPServer1Execute(AContext: TIdContext);
var
  bufRecv: TMemoryStream;
begin
  if Not(AContext.Connection.Connected) then Exit;  //未连接时退出

  bufRecv:=TMemoryStream.Create;
  try
    //一直接收 直到连接断开
    while AContext.Connection.Connected do
    begin
      AContext.Connection.IOHandler.ReadStream(bufRecv, -1, True);
    end;
    //数据接收完毕
    bufRecv.Seek(0, soFromBeginning);
    Memo_out.Lines.LoadFromStream(bufRecv);
  finally
    bufRecv.Free;
  end;
end;

 

UDP就比较简单了,放个按钮,一个TIdUDPServer
TIdUDPServer绑定 0.0.0.0:3820,然后Active设置为True

//发送按钮
procedure TForm1.Button1Click(Sender: TObject);
var
  IdUDPClient1: TIdUDPClient;  //动态创建TIdUDPClient
begin
  IdUDPClient1:=TIdUDPClient.Create;
  IdUDPClient1.BroadcastEnabled:=true;

  try
    IdUDPClient1.Port:=3820;
    IdUDPClient1.Host:='127.0.0.1';

    IdUDPClient1.Connect;            //实际上就这三句
      IdUDPClient1.Send('abcdefg.'); //2
    IdUDPClient1.Disconnect;         //3
  finally
    IdUDPClient1.Free;
  end;
end;

//IdUDPServer1 绑定3820端口
//注意引用 IdSocketHandle, IdGlobal
procedure TForm1.IdUDPServer1UDPRead(Sender: TObject; AData: TBytes;
  ABinding: TIdSocketHandle);
var
  StrBuf: String absolute AData;
begin
  Memo1.Lines.Add(StrBuf);   //把接收的信息加到Memo1
end;

 






















































































文章来自: 网络采集
Tags: 暂无标签
评论:   | 查看次数:  
正在读取日志的评论数据,请稍后……
正在加载日志评论签写框,请稍后……