[英]UDP in Seattle vs Delphi 7
這段代碼在Delphi 7下運行良好:
procedure TForm1.FormCreate(Sender: TObject);
//var IdUDPClient1: TIdUDPClient;
begin
idudpclient1.host := '127.0.0.1';
idudpclient1.port := 1234;
idudpclient1.Binding.Port := 1234;
idudpclient1.Binding.Bind;
idudpclient1.Send('Hello');
end;
在Delphi 10 Seattle 32位窗口下運行完全相同的代碼會導致套接字運行時錯誤10022:參數無效,然后無法綁定套接字,地址和端口已在使用中。
有任何想法嗎?
最好的問候托馬斯·里德爾
在Indy 10中,當您訪問Binding
屬性時,將創建並綁定套接字(如果尚未綁定) 。 因此,您嘗試在已綁定的套接字上調用Bind()
。
當底層套接字API bind()
失敗時,將引發“無效參數”錯誤。 根據MSDN的bind()
文檔:
WSAEINVAL
提供了無效的參數。返回的錯誤已將套接字
s
已綁定到一個地址 。
TIdSocketHandle.Bind()
調用TIdSocketHandle.TryBind()
,而TryBind()
捕獲“無效參數”錯誤,因此,只有在調試器中運行代碼時,您才應該看到它。 “無法綁定套接字”錯誤是Indy自身的錯誤,如果TryBind()
失敗, TIdSocketHandle.Bind()
會引發該錯誤。
根本不應該直接設置Binding.Port
或直接調用Binding.Bind()
。 改用TIdUDPClient.BoundPort
屬性(以及可選的TIdUDPClient.BoundIP
):
procedure TForm1.FormCreate(Sender: TObject);
//var IdUDPClient1: TIdUDPClient;
begin
IdUDPClient1.Host := '127.0.0.1';
IdUDPClient1.Port := 1234;
//IdUDPClient1.BoundIP := '127.0.0.1';
IdUDPClient1.BoundPort := 1234;
IdUDPClient1.Send('Hello');
end;
當TIdUDPClient
分配其套接字時,它將為您調用Bind()
,將BoundPort
分配給Binding.Port
(並將BoundIP
給Binding.IP
)。
您的代碼在Delphi 7中起作用的原因是因為您使用的是Indy 9(或更早版本)而不是Indy10。在那些較早的Indy版本中,訪問Binding
屬性僅分配了套接字,它也沒有綁定套接字,因此您能夠手動綁定它。 這已不再是這種情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.