服务端:
var
addr : sockaddr_in;
fd,cnt : integer;
mess : array[1..1024] of char;
Paddr : ^sockaddr_in;
i : integer;
// mreq : ip_mreq;
begin
Mult_Group := Edit1.Text ;
Mult_Port := 12345;
fd := socket(AF_INET,SOCK_DGRAM,0);
if (fd < 0) then
begin
showmessage('socket error');
exit;
end;
fillchar(addr,sizeof(sockaddr_in),0);
addr.sin_family := AF_INET;
addr.sin_addr.S_addr := inet_addr(PChar(Mult_Group));
addr.sin_port := Mult_Port;
// Paddr^ := addr;
i:=0;
while i<30 do
begin
strcopy (@mess,pchar(Edit3.text+inttostr(i)));
Memo1.Lines.Add (mess);
if Memo1.Lines.Count >200 then Memo1.Clear ;
if (sendto(fd,mess,sizeof(mess),0,addr,sizeof(addr))<0) then
begin
showmessage('sendto error');
exit;
end;
I:=i+1;
lblSend.Caption := inttostr(i);
sleep(1000);
end;
closesocket(fd);
//----------------------------------------------------------------
接收端:
var
addr : sockaddr_in;
fd,NBYTES,ADDRLEN : integer;
mreq : ip_mreq;
mess : array[1..1024] of char;
i : integer;
// mreq : ip_mreq;
begin
Mult_Group := Edit2.Text ;
Mult_Port := 12345;
fd := socket(AF_INET,SOCK_DGRAM,0);
if (fd < 0) then
begin
showmessage('socket error');
exit;
end;
fillchar(addr,sizeof(sockaddr_in),0);
// strcopy (@mess,pchar(Edit3.text));
addr.sin_family := AF_INET;
addr.sin_addr.S_addr := htonl(INADDR_ANY);
addr.sin_port := Mult_Port;
if (bind(fd,addr,sizeof(addr))<0) then
begin
showmessage('bind error');
exit;
end;
mreq.imr_multiaddr.S_addr := inet_addr(pchar(Mult_Group));
mreq.imr_interface.S_addr := htonl(INADDR_ANY);
if (setsockopt(fd,IPPROTO_IP,IP_ADD_MEMBERSHIP,@mreq,sizeof(mreq))<0) then
begin
showmessage('setsockopt error');
exit;
end;
i := 0 ;
while i<20 do
begin
addrlen := sizeof(addr);
nbytes := recvfrom(fd,mess,sizeof(mess),0,addr,addrlen);
if nbytes <0 then
begin
showmessage('recvfrom error');
exit;
end;
i:=i+1;
lblReceive.Caption := inttostr(i);
Memo2.Lines.Add(trim(mess));
if Memo2.Lines.Count >200 then Memo2.Clear ;
// showmessage(mess);
end;
closesocket(fd);
//-----------------------------------------------------
这里是我以前写的程序中的一段测试代码,没有整理,但肯定没问题。