0

So I'm writing two applications, one console application and one background/windows application. These two applications are made to communicate with eachother through TCP (I'm using TcpClient class and TcpListener class). The problem I have is that when I change the Output type of the background application from Console to Windows application the encoding gets kind of messed up and the output on the server (console server) prints some characters as gibberish.

I've tried setting different encodings for the socket streams but nothing seems to work.

TcpClient client = new TcpClient();
socketInput = new StreamWriter(client.GetStream());
socketOutput = new StreamReader(client.GetStream());

...

process.OutputDataReceived += new 
DataReceivedEventHandler(p_OutputDataReceived);

...

static void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
    {
        if (!String.IsNullOrEmpty(e.Data))
        {
            StringBuilder strOutput = new StringBuilder();

            try
            {
                strOutput.Append(e.Data);
                Console.WriteLine(strOutput);
                socketInput.WriteLine(strOutput);
                socketInput.Flush();
            }
            catch (Exception ex) { }
        }
    }
Johnny Code
  • 39
  • 2
  • 6
  • You can specify a particular encoding to be used by a StreamReader/TextReader. It's documentation can tell you all the dirty details about how to do that (https://learn.microsoft.com/en-us/dotnet/api/system.io.streamreader?view=netframework-4.7.2#constructors). Similarly, you can specify an encoding to be used for the console output. (Check the documentation for the `Console` class). Note that the console might not be able to show particular characters properly if the font used for the console does not contain glyphs for such characters. –  Mar 23 '19 at 18:01
  • With regard to console encoding and console font, see here: https://stackoverflow.com/questions/5750203/how-to-write-unicode-characters-to-the-console –  Mar 23 '19 at 18:06
  • I've been mixing around with different encodings alot and nothing seems to work here. When I have the client program as Console Application everything works smooth as ever even if I don't define any specific encodings. But when i switch it to Windows application (to make it run in the background) some special characters get outputted as gibberish on the serverside console. – Johnny Code Mar 23 '19 at 18:36
  • I am not sure i understand your last comment correctly, but you should use the same encoding for all parties (StreamReader/StreamWriter/Console output/whatever), not mix different encodings. –  Mar 23 '19 at 19:32

0 Answers0