1

I'm trying to remove all CRLF characters from the string dataFromClient in the C# code bellow. All of the following attempts have failed so far and I'd be very thankful for your help:

edit: The problem is that whenever the Console.WriteLine(dataFromClient) method is called, the string prints but looks like this: "\vposition?:X\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0....." I want the output to only be "position?:X". But have not been able to trim the "\0" from the string.

This code is my first attempt at setting up a simple server to accept a connection form a third party software. Requests are made from the client, then this server parses the request to commands that a motorized Cartesian stage understands.

Bellow is the code from the server portion/ class of the console app.

Posts with suggestions I already tried:

Removing carriage return and new-line from the end of a string in c#

Serial communication and CRLF C#

How to WriteAllLines in C# without CRLF

Remove a character from a string

String Trim Spaces doesn't work

Here is the code:

using System;
using System.Net;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace autotile_V001
{
    public class Myserver
    {
        int MyServerPort;
        bool go = true;
        int requestCount = 0;
        string dataFromClient;
        string serverResponse;
        IPAddress ipAddr = IPAddress.Loopback;

        public string process(string s)
        {
            int len = s.Length;
            int current = 0;
            StringBuilder sb = new StringBuilder(len);

            while (current < len - 1)
            {
                if ((s[current] == ' ' && s[current + 1] == ' '))
                {
                    break;
                }
                else
                {
                    sb.Append(s[current]);
                }
                current++;
            }
            return sb.ToString();
        } 

        public void StartMyServer()
        {
            TcpListener serverSocket = new TcpListener(ipAddr, MyServerPort);
            TcpClient clientSocket = default(TcpClient);
            serverSocket.Start();
            Console.WriteLine(" >> Server Started");
            clientSocket = serverSocket.AcceptTcpClient();
            Console.WriteLine(" >> Accepted connection from client");
            requestCount = 0;

            while ((go))
            {
                try
                {
                    requestCount++;
                    NetworkStream networkStream = clientSocket.GetStream();
                    byte[] bytesFrom = new byte[(int)clientSocket.ReceiveBufferSize];
                    networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
                    dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);

                    Console.WriteLine(" >> Data from client - {0}", (String.Join("\n", dataFromClient)).Trim());

                    serverResponse = Console.ReadLine();

                    Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);

                    networkStream.Write(sendBytes, 0, sendBytes.Length);
                    networkStream.Flush();
                    Console.WriteLine(" >> " + serverResponse);

                    go = true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());

                    go = false;
                }
            }
        }

        public Myserver(int someData)
        {
            MyServerPort = someData;
        }
    }
}
Community
  • 1
  • 1
Pierre
  • 15
  • 1
  • 8
  • 4
    It looks like you pushed `Submit` a bit early? Please can you complete the question and provide the code? – StuartLC Nov 23 '14 at 06:42
  • Hi StuartLC, you're right. I accidentally hit the return key while typing as the mouse pointer was focused outside another window. – Pierre Nov 23 '14 at 06:57
  • Please describe precisely, and without sending anyone to a separate web site to download a screenshot, what your actual question is. Provide a concise, complete, _minimal_ code example. State in specific detail what happens when the code is run, and how that is different from what you want. See http://stackoverflow.com/help/mcve and http://stackoverflow.com/help/how-to-ask – Peter Duniho Nov 23 '14 at 07:22
  • Could it be because of using `Console.WriteLine()` which adds `CRLF` at the end of each output? Thoughts? – Vivek Jain Nov 23 '14 at 07:46
  • I would start with checking what exactly is in the dataFromClient before printing. I would also look at the String.Join - you feed it with a string, not array of strings, and I suspect it adds \n after each character. – MirekE Nov 23 '14 at 07:51
  • Hi MirekE, here is the value of dataFromClient during execution:"\vposition?:X\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\....." – Pierre Nov 23 '14 at 15:41
  • Hi MirekE. I just found the answer in this thread:http://stackoverflow.com/questions/3387733/how-to-remove-0-from-a-string-in-c thank you very much, I'm new to Visual Studio and programming c# overall. thanks again. – Pierre Nov 23 '14 at 16:08

1 Answers1

3

Trim() just removes leading and trailing whitespace - not whitespace within a string.

You'll need to use Replace to remove out unwanted characters or strings from inside a string. In the case above, any trialing non-white space character (which might not be visible, e.g. 0x0) in the byte stream will cause the call to Trim not to work.

var someString = "FOO\r\n\r\n\0";
var strippedTrim = someString.Trim();  // Fail - "FOO\r\n\r\n\0"
var strippedReplace = someString.Replace("\r\n", ""); // "FOO\0"
// .Replace() any other unwanted white space, e.g. "\t"

Noted however that Trim() will still remove a trailing naked '\n' (as opposed to Windows CRLF), so it isn't the String.Join("\n" causing the bug.

Edit

Just to clarify the string.Join - string.Join when used on a single string is redundant / has no effect (neither does it treat the string as an array of single character strings).

var join = string.Join("x", "FOO\r\n\r\n").Trim(); // Works - "FOO"
StuartLC
  • 104,537
  • 17
  • 209
  • 285