我在尝试使用TIdUDPServer的OnUDPRead事件来读取从我创建的IdUDPClient客户端发送的广播数据时遇到问题。我尝试过使用以下问题中显示的示例但无济于事。
How can I send a broadcast message in Delphi
Reading data with TIdUDPServer
我能够将TIdUDPServer绑定到我指定的端口:
procedure TForm1.Button1Click(Sender: TObject);
begin
IdUDPServer1.BroadcastEnabled := True;
IdUDPServer1.DefaultPort := StrToInt(edit2.Text);
IdUDPServer1.Bindings.Add.IP := '0.0.0.0';
//IdUDPServer1.ThreadedEvent:=True;
IdUDPServer1.Active := True;
end;
成功触发IdUDPServer1UDPRead,显示UDP服务器正在运行,但我在此行获得了一个例外 - > DataStringStream.CopyFrom(AData,AData.Size);
异常:模块中地址004BA415的访问冲突 ' IndyUDPReceiver.exe&#39 ;.阅读地址74736574
procedure TForm1.IdUDPServer1UDPRead(Sender: TObject;
AData: TStream; ABinding: TIdSocketHandle);
var
DataStringStream: TStringStream;
msg: string;
begin
try
DataStringStream := TStringStream.Create('');
try
DataStringStream.CopyFrom(AData, AData.Size);
msg := DataStringStream.DataString;
Memo1.Lines.Add(msg);
finally
DataStringStream.Free;
end;
except
on E: Exception do
begin
Memo1.Lines.Add('Exception:' + E.Message);
DataStringStream.Free;
end;
end;
end;
我已将完整的客户端和服务器上传到:http://www.2shared.com/file/5SRweGIa/Indy_UDP.html
感谢任何指针。 :)
答案 0 :(得分:2)
您是否偶然从旧版本的Delphi和/或Indy升级您的项目,并忘记检查您的事件处理程序是否有签名更改?很久以前,TIdUDPServer.OnUDPRead
事件使用TStream
停止了AData
参数。它改为使用TIdBytes
代替:
procedure TForm1.IdUDPServer1UDPRead(AThread: TIdUDPListenerThread; const AData: TIdBytes; ABinding: TIdSocketHandle);
var
msg: string;
begin
msg := BytesToString(AData, Indy8BitEncoding);
Memo1.Lines.Add(msg);
end;
几个星期前,我们不得不更改XE3的AData
参数,以便最终解决所有2009 +版本中Delphi和C ++之间的RTTI不兼容问题:
procedure TForm1.IdUDPServer1UDPRead(AThread: TIdUDPListenerThread; const AData: array of Byte; ABinding: TIdSocketHandle);
var
msg: string;
begin
msg := BytesToString(AData, Indy8BitEncoding);
Memo1.Lines.Add(msg);
end;