我必须从C ++客户端接收UDP数据报。客户端正常工作并将数据报发送到我编译此代码的ip。数据报的大小为800字节。当我发送数据报时,读取过程被阻止。我在此示例后创建了此代码:{{3}},这在我的主机上完美运行。有什么想法吗?
procedure RECEIVE_DATA (
DEST_UDP_PORT : In WORD_TYPE;
SRC_UDP_PORT : In WORD_TYPE;
WAIT_TIME : In DURATION;
MESSAGE_ADDRESS : Out System.Address;
WAIT_RESULT : Out Boolean
) is
task Receive is
entry Start;
end Receive;
task body Receive is
Address : Sock_Addr_Type;
Socket : Socket_Type;
Channel : Stream_Access;
Receive_Timeout : constant Duration := WAIT_TIME;
Offset : Ada.Streams.Stream_Element_Count;
Data : Ada.Streams.Stream_Element_Array (1 .. 800);
begin
accept Start;
Initialize;
WAIT_RESULT := False;
Create_Socket (Socket, Family_Inet, Socket_Datagram);
Set_Socket_Option (Socket => Socket,
Option => (Gnat.Sockets.Receive_Timeout, Timeout => Receive_Timeout));
Address.Addr := Inet_Addr(DEST_UDP_IP);
Address.Port := Port_Type(DEST_UDP_PORT);
Bind_Socket (Socket, Address);
Address.Addr := Inet_Addr(SRC_UDP_IP);
Address.Port := Port_Type(SRC_UDP_PORT);
Channel := Stream (Socket, Address);
loop
Ada.Streams.Read (Channel.All, Data, Offset);
exit when Offset = 0;
end loop;
Free (Channel);
Close_Socket (Socket);
WAIT_RESULT := True;
MESSAGE_ADDRESS := Data'Address;
exception when E : others =>
Ada.Text_IO.Put_Line
(Exception_Name (E) & ": " & Exception_Message (E));
WAIT_RESULT := False;
Free (Channel);
Close_Socket (Socket);
end Receive;
begin
Initialize (Process_Blocking_IO => False);
Receive.Start;
Finalize;
end RECEIVE_DATA;
答案 0 :(得分:3)
您是否尝试过使用GNAT.Sockets.Receive_Socket? Streams使用TCP,您无法流式传输数据报。
示例:
客户端:
file.exists(n)
服务器:
with Ada.Streams;
with Ada.Text_IO;
with GNAT.Sockets;
procedure UDP_Client is
use GNAT.Sockets;
Address : Sock_Addr_Type;
Socket : Socket_Type;
Data : constant Ada.Streams.Stream_Element_Array (1 .. 512) := (others => 42);
Last : Ada.Streams.Stream_Element_Offset;
begin
Address.Port := 50001;
Address.Addr := Inet_Addr ("127.0.0.1");
Create_Socket (Socket, Family_Inet, Socket_Datagram);
Send_Socket (Socket, Data, Last, Address);
Ada.Text_IO.Put_Line ("last :" & Last'Img);
end UDP_Client;