Claudio Ferreira
Claudio Ferreira

Reputation: 171

Indy 10 TidTCPServer encoding characters

Indy 10 Sockets . TIdTCPServer component . There is a client program that connects to a server program using sockets. Everything working , there is no trouble in communicating , but I can not send a string with special characters from the server to the client. When sending a string like this:

         AContext.Connection.IOHandler.WriteLn ( ' Usuário não existe' ) ;

Client receives the string :

usu?rio n?o existe

Anyone who has ever worked with this component knows how do I set the encoding correctly and to send this special string to the client ?

Upvotes: 2

Views: 7919

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596196

By default, Indy uses 7bit ASCII as its character encoding (for compatibility with various Internet protocols). To use a different character encoding, you need to either:

  1. set the IOHandler.DefStringEncoding property before doing any reading/writing. The string-based I/O methods will then use this encoding by default.

    // note: use TIdTextEncoding.UTF8 if not using Indy 10.6 or later...
    AContext.Connection.IOHandler.DefStringEncoding := IndyTextEncoding_UTF8;
    
  2. use the optional AByteEncoding parameter of the various string-based I/O methods, including WriteLn().

    // note: use TIdTextEncoding.UTF8 if not using Indy 10.6 or later...
    AContext.Connection.IOHandler.WriteLn('Usuário não existe', IndyTextEncoding_UTF8);
    

Needless to say, the client will also have to use an equivalent encoding when reading the server's data so it can decode the transmitted bytes back to Unicode. For example:

// note: use TIdTextEncoding.UTF8 if not using Indy 10.6 or later...
Client.IOHandler.DefStringEncoding := IndyTextEncoding_UTF8;

Or:

// note: use TIdTextEncoding.UTF8 if not using Indy 10.6 or later...
S := Client.IOHandler.ReadLn(IndyTextEncoding_UTF8);

Upvotes: 7

Related Questions