代码贴出来,也许可以给有需要的人参考一下.
unit AdmyUdpReceiver;
interface
uses
Messages, Classes, Controls, WinSock;
const
WM_SOCK = WM_USER+1;
//自定义windows消息
type
TDataReceivedEvent = procedure(Sender: TComponent;
NumberBytes: Integer;Buffer:array of char) of object;
TAdmyUdpReceiver=class(TWinControl)
private
FSocket: TSocket;
FPort: u_short;
FSocketOK: boolean;
FDataReceived: TDataReceivedEvent;
procedure ReadData(var Message: TMessage);
message WM_SOCK;
published
property OnDataReceived: TDataReceivedEvent read FDataReceived write FDataReceived;
constructor Create(AOwner: TComponent);
override;
destructor Destroy;
override;
procedure InitSocket(port:integer);
end;
implementation
{ TAdmyUdpReceiver }
constructor TAdmyUdpReceiver.Create(AOwner: TComponent);
var
TempWSAData: TWSAData;
begin
inherited Create(AOwner);
FSocketOK:=false;
if WSAStartup($101, TempWSAData)=1 then
exit;
// showmessage('StartUp Error!');
FSocket := Socket(AF_INET, SOCK_DGRAM, 0);
if (FSocket = INVALID_SOCKET) then
//Socket创建失败
begin
// showmessage(inttostr(WSAGetLastError())+' Socket创建失败');
CloseSocket(FSocket);
end;
FSocketOK:=true;
end;
destructor TAdmyUdpReceiver.Destroy;
begin
if FSocketOK then
CloseSocket(FSocket);
inherited;
end;
procedure TAdmyUdpReceiver.InitSocket(port: integer);
var
addr: TSockAddr;
begin
if not FSocketOK then
exit;
addr.sin_family := AF_INET;
addr.sin_addr.S_addr := INADDR_ANY;
FPort:=port;
addr.sin_port := htons(FPort);
if Bind(FSocket, addr, sizeof(addr)) <> 0 then
begin
exit;
//showmessage('bind fail');
end;
WSAAsyncSelect(FSocket, self.Handle , WM_SOCK, FD_READ);
end;
procedure TAdmyUdpReceiver.ReadData(var Message: TMessage);
var
buffer: Array [1..32768] of char;
//最大可接收字节数
len: integer;
flen: integer;
Event: word;
// value: string;
FSockAddrIn : TSockAddrIn;
begin
flen:=sizeof(FSockAddrIn);
FSockAddrIn.SIn_Port := htons(FPort);
Event := WSAGetSelectEvent(Message.LParam);
if Event = FD_READ then
begin
try
len := recvfrom(FSocket, buffer, sizeof(buffer), 0, FSockAddrIn, flen);
except
len:=-1;
end;
if assigned(FDataReceived) then
FDataReceived(self,len,buffer);
end;
end;
end.