简体   繁体   中英

Unable to remove CRLF from string in c#

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;
        }
    }
}

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, eg 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM