Delphi中TUDPSocket的使用

   2023-02-09 学习力0
核心提示:        按照Delphi文档上所说,欲在两个socket之间通信,必须一个为client,一个为server。这个概念在TCP上还好说,但是用在UDP上就不大合适了。borland提供的UDP组件只有一个TUDPSocket,按照borland的说法,TUDPSocket即可以作为client也可以作为se

        按照Delphi文档上所说,欲在两个socket之间通信,必须一个为client,一个为server。这个概念在TCP上还好说,但是用在UDP上就不大合适了。borland提供的UDP组件只有一个TUDPSocket,按照borland的说法,TUDPSocket即可以作为client也可以作为server使用(UDP下,server与client的区别并不明显,但为了方便我们不妨这么称呼)(参考 turbo delphi win32 developer's guide里的Using Client Sockets和Using Server Sockets)。但是通过源码我们不难发现,TUDPServer是继承于TCustomIPClient的。它被设计为只能当作一个客户端来用。

        通过参考vc++的范例程序得知UDP通信时,server端要做的工作有:open->bind->send/recv->close,其中bind这步很重要,它将一个socket绑定到一个本地地址。document上的原话是:

    This routine is used on an unconnected connectionless or connection-oriented socket, before subsequent connects or listens. When a socket is created with socket, it exists in a name space (address family), but it has no name assigned. bind establishes the local association of the socket by assigning a local name to an unnamed socket.

“这个例程在连接(无连接)与监听(面向连接)之前调用...bind把一个本地的名字绑定到了一个socket上”

        监听是TCPServer的动作,那么相对应的,在UDP中作为Server使用的socket也应当调用bind()。可是在borland提供的socket.pas中bind一共出现了5次,4次在TIPSocket,还有一次出现在TCustomTCPServer。前四次是对socket API的封装,最后一次也是这个.pas中唯一的一次对bind的调用。就是这个bind使TUDPSocket“沦为”了一个客户端。

      TUDPSocket的Open方法会依次建立一个socket,设置好远端地址和端口,然后就自动连接了。没有bind。而唯一的会调用bind的TTCPServer,它在bind后则自动进入了监听状态。对于UDP来说,我们不希望它监听,要达到这个目的,除了写自己的类以外,我们只能从它们的父类入手。

通过观察发现,TIPSocket实现了bind的封装,并且它的open方法继承于TBaseSocket——只完成了socket的创建,这恰恰是我们所需要的。我们只需要手动bind这个socket即可。

 

源码如下,turbo delphi 2006(ver100)调试通过:

 

{server端设置}

program UDPServer;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  Sockets,
  WinSock;

const
  DefaultPort='827';
var
  aUDPServer  : TIPSocket;
  addr        : TSockAddr;
  rv,i        : integer;
  quit        : boolean;
  buf         : array [0..255] of byte;
begin
  { TODO -oUser -cConsole Main : Insert code here }
  quit:=false;
  aUDPServer:=TIPSocket.Create(nil);

  aUDPServer.LocalHost:=aUDPServer.LocalHostName;
  aUDPServer.LocalPort:=DefaultPort;
  aUDPServer.Protocol:=IPPROTO_UDP;
  aUDPServer.SockType:=stDgram;
  //aUDPServer.BlockMode:=bmNonBlocking;
  aUDPServer.Active:=true;
  addr:=aUDPServer.GetSocketAddr(aUDPServer.LocalHost,aUDPServer.LocalPort);
  bind(aUDPServer.Handle,addr,sizeof(addr));
  while not quit do
  begin
    fillchar(buf,255,0);
    rv:=aUDPServer.Receivebuf(buf,sizeof(buf));
    if rv<>Socket_Error then
    begin
      for i:=0 to rv do write(inttohex(buf[i],2),' ');
      writeln;
      for i:=0 to rv do write(chr(buf[i]));
      writeln;
    end;
  end;

  if assigned(aUDPServer) then
    aUDPServer.Free;
end.
{client端}
unit UUDPClient;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Sockets;

type
  TForm1 = class(TForm)
    UdpSocket1: TUdpSocket;
    Button1: TButton;
    Edit1: TEdit;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}
const
  DefaultPort = '827';
procedure TForm1.FormCreate(Sender: TObject);
begin
  with UdpSocket1 do
  begin
    RemoteHost:='121.195.43.77';
    RemotePort:=DefaultPort;
    Active:=true;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  buf : array [1..256] of byte;
  i:integer;
begin
  fillchar(buf,length(buf),0);
  if length(edit1.Text)<length(buf) then
  begin
    for i:=1 to length(edit1.Text) do buf[i]:=byte(edit1.Text[i]);
    UDPSocket1.SendBuf(buf,length(edit1.Text));
  end;
end;

end.

 

 
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

  • Delphi中的消息处理机制 delphi 方法
    每一个VCL都有一内在的消息处理机制,其基本点就是构件类接收到某些消息并把它们发送给适当的处理方法,如果没有特定的处理方法,则调用缺省的消息处理句柄。    其中mainwndproc是定义在Twincontrol类中的一个静态方法,不能被重载(Override)。它不直接处
    02-09
  • Delphi XE6 通过JavaScript API调用百度地图
    Delphi XE6 通过JavaScript API调用百度地图
    参考昨天的内容,有朋友还是问如何调用百度地图,也是,谁让咱都在国内呢,没办法,你懂的。 首先去申请个Key,然后看一下百度JavaScript的第一个例子:http://developer.baidu.com/map/jsdemo.htm下一步,就是把例子中的代码,移动TWebBrower中。 unit Unit
    02-09
  • Delphi编译/链接过程 delphi编程案例
    Delphi编译/链接过程 delphi编程案例
    下面展示了Delphi是怎样编译源文件,并且把它们链接起来,最终形成可执行文件。当Delphi编译项目(Project)时,将编译项目源文件、窗体单元和其他相关单元,在这个过程中将会发生好几件事情:首先,Object Pascal编译器把项目单元编译为二进制对象文件,然后
    02-09
  • Delphi CompilerVersion Constant / Compiler C
    http://delphi.wikia.com/wiki/CompilerVersion_Constant The CompilerVersion constant identifies the internal version number of the Delphi compiler.It is defined in the System unit and may be referenced either in code just as any other consta
    02-09
  • Delphi revelations #1 – kbmMW Smart client
    Delphi 启示 #1 – kbmMW Smart client on NextGen (Android) – 作用域问题以更高级的方式使用kbmMW smart client,在Android设备上,我遇到了问题。通过继承TInvokeableVariantType,kbmMW smart client可以使用Delphi支持的特殊类型的自定义Variant,从而可
    02-09
  • Delphi 调用DLL外部函数时的指针参数
    某项目需要调用设备厂家提供的DLL的函数,厂家给了一个VB的例子,有个参数是ByRef pBuffer As Single。于是在Delphi中用buffer:array of single代替:function func(buffer:array of single;count:integer):integer;far;stdcall;external 'func.dll';调用后bu
    02-09
  • 《zw版·Halcon-delphi系列原创教程》 Halcon分
    《zw版·Halcon-delphi系列原创教程》 Halcon分类函数012,polygon,多边形为方便阅读,在不影响说明的前提下,笔者对函数进行了简化::: 用符号“**”,替换:“procedure”:: 用大写字母“X”,替换:“IHUntypedObjectX”:: 省略了字符:“const”、“OleVa
    02-09
  • 最简单的delphi启动画面(转)
    首先做一窗体,然后将BorderStyle的属性设为bsnone,放image控件,align设为alclient 然后将主程序的修改为 uses Windows, Forms, Unit1 in 'Unit1.pas' {Form1}, Unit2 in 'Unit2.pas' {Form2}; {$ R *.res} begin Application.Initialize; Form2:=TForm2.Cre
    02-09
  • Delphi备忘三:TCollection的使用,用Stream保
     代码unit ufrmGetFunctionDefine;interfaceuses  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,TypInfo,  Dialogs,ufrmStockBaseCalc, StdCtrls, ComCtrls,uQEFuncManager,uWnDataSet,uDataService;type  T
    02-09
  • Delphi Dcp 和BPL的解释
    dcp = delphi compiled package,是 package 编译时跟 bpl 一起产生出来的,记录着 package 中公开的 class、procedure、function、variable、const.... 等等的名称和相对位址。package英文翻译过来就是“包”。如果 某个控件包 A 引用了 控件包 B,当 控件包
    02-09
点击排行