用Idtcpserver组件收发中文,关键就是转码,要将编码转为UTF-8格式。
接收消息
procedure TfrmMain.IdTCPServerExecute(AContext: TIdContext);
var BufStr:AnsiString;
buflen:integer;
begin
if (AContext.Connection.Connected) then
begin
try
CoInitialize(nil);
try
BufStr:=AContext.Connection.IOHandler.ReadLn(TIdEncoding.en8Bit);
LogMsg('read: '+BufStr+' '+'IP:'+AContext.Connection.Socket.Binding.PeerIP+':'+intToStr(AContext.Connection.Socket.Binding.PeerPort));
except
AContext.Connection.Disconnect;
end;
buflen:=Length(BufStr);
finally
CoUninitialize();
end;
end;
end;
发送消息
procedure TfrmMain.SendClientMessage(AContext: TIdContext; sMsg: string);
var sClientID:string;
begin
if TIdContext(AContext).Connection.Connected then
begin
sClientID:=TIdContext(AContext).Connection.Socket.Binding.PeerIP+':'+intToStr(TIdContext(AContext).Connection.Socket.Binding.PeerPort);
AContext.Connection.IOHandler.WriteLn(sMsg,TIdEncoding.en8Bit);
LogMsg('Send: '+sMsg+' '+'IP:'+sClientID);
end;
end;