[英]Convert From indy udp To Tcp
我一直在使用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
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;
我如何使它們在indy 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;
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.