Delphi 从indy udp转换为Tcp
我一直在使用indy udp,我想继续使用indy tcp 但我不知道如何将代码转换为与indy tcp相同的工作方式 我的项目工作发送流作为聊天室这里是udp代码Delphi 从indy udp转换为Tcp,delphi,indy,Delphi,Indy,我一直在使用indy udp,我想继续使用indy tcp 但我不知道如何将代码转换为与indy tcp相同的工作方式 我的项目工作发送流作为聊天室这里是udp代码 procedure TForm1.recorderData(Sender: TObject; const Buffer: Pointer; BufferSize: Cardinal; var FreeIt: Boolean); begin Freeit :=True; if IDUDPCLIENT.active then IDU
procedure TForm1.recorderData(Sender: TObject; const Buffer: Pointer;
BufferSize: Cardinal; var FreeIt: Boolean);
begin
Freeit :=True;
if IDUDPCLIENT.active then
IDUDPCLIENT.SendBuffer(RawToBytes(Buffer^, Buffersize))
else
stop.Caption := 'error';
end;
这是服务器上的读取事件
procedure TForm1.UDPReceiverUDPRead(AThread: TIdUDPListenerThread; const AData: TIdBytes; ABinding: TIdSocketHandle);
var
AudioDataSize: Integer;
AudioData : Pointer;
begin
try
EnterCriticalSection(Section);
try
AudioDataSize := Length(AData);
if AudioDataSize > 10 then
begin
try
if not Player.Active then
begin
Player.Active := True;
Player.WaitForStart;
end;
except
end;
if BlockAlign > 1 then Dec(AudioDataSize, AudioDataSize mod BlockAlign);
AudioData := AudioBuffer.BeginUpdate(AudioDataSize);
try
BytesToRaw(AData, AudioData^, AudioDataSize);
finally
AudioBuffer.EndUpdate;
end;
end else
begin
Player.Active := False;
Player.WaitForStop;
end;
finally
LeaveCriticalSection(Section);
end;
except
end;
end;
我是如何让它们在印地tcp中以同样的方式工作的 Indy的UDP和TCP组件使用不同的接口架构。仅仅移植代码是不够的,您必须相应地重新设计通信协议,这可能需要您重新编写核心代码逻辑。请记住,UDP是基于消息的,但TCP不是,因此您必须设计自己的消息帧 您还必须考虑到,像
TIdUDPServer
,TIdTCPServer
也是多线程的。但与TIdUDPServer
不同,TIdTCPServer
没有ThreadedEvent
属性,因此在访问其他线程时,尤其是主UI线程时,您必须提供自己的同步
根据您的简单示例,尝试以下操作:
procedure TForm1.recorderData(Sender: TObject; const Buffer: Pointer; BufferSize: Cardinal; var FreeIt: Boolean);
begin
FreeIt := True;
try
if IdTCPClient1.Connected then
begin
IdTCPClient1.IOHandler.Write(BufferSize);
IdTCPClient1.IOHandler.Write(RawToBytes(Buffer^, BufferSize));
Exit;
end;
except
end;
stop.Caption := 'error';
end;
谢谢你,remy,这对我帮助很大。还有一件事,remy我正试图用udp发送消息,我正在做这个iDCLIENT.Broadcast(strMsg,16000);阅读如下msg.Lines.Add(BytesToString(AData));如何在tcp中实现?tcp不支持广播。您必须向您拥有的每个TCP连接发送消息数据的单独副本。
procedure TForm1.IdTCPServer1Execute(AContext: TIdContext);
var
AudioDataSize: Integer;
AudioDataBytes: TIdBytes;
AudioData: Pointer;
begin
AudioDataSize := AContext.Connection.IOHandler.ReadLongInt();
AContext.Connection.IOHandler.ReadBytes(AudioDataBytes, AudioDataSize);
EnterCriticalSection(Section);
try
if AudioDataSize > 10 then
begin
try
if not Player.Active then
begin
Player.Active := True;
Player.WaitForStart;
end;
except
end;
if BlockAlign > 1 then Dec(AudioDataSize, AudioDataSize mod BlockAlign);
AudioData := AudioBuffer.BeginUpdate(AudioDataSize);
try
BytesToRaw(AudioDataBytes, AudioData^, AudioDataSize);
finally
AudioBuffer.EndUpdate;
end;
end else
begin
Player.Active := False;
Player.WaitForStop;
end;
finally
LeaveCriticalSection(Section);
end;
end;