Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8818847
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T05:12:28+00:00 2026-06-14T05:12:28+00:00

I’m sending data between a server and a client using TCP. I send a

  • 0

I’m sending data between a server and a client using TCP. I send a stream of bytes, so I convert the strings to byte arrays, send to the client, then convert it back to a string. Then I insert this string into a multiline textbox with Environment.NewLine after each one. However, a new line isn’t appearing.

I’ve tried multiple ways of converting the string to arrays and back to strings all with the same result. Environment.NewLine doesn’t work. \n\r doesn’t work.

I’ve tried converting using the following techniques:

  1. Encoding.ASCII.GetString() and Encoding.ASCII.GetBytes()
  2. Encoding.Unicode.GetString() and Encoding.Unicode.GetBytes()
  3. I’ve also used the code on the following website which uses:

    System.Text.UTF8Encoding encoding=new System.Text.UTF8Encoding();

    String to Byte Array Conversion in C# and VB.NET (and back)

How should I convert these strings back and forth to get this to work? My client is currently C# but is going to be java in production.

EDIT:

    AttachMessage(ByteArrayToStr(messageInByteArray)); // Doesn't work
    AttachMessage("TEST"); // works


    public void AttachMessage(string data)
    {
        textBox2.Text += data + Environment.NewLine;
    }

    public static string ByteArrayToStr(byte[] arr)
    {
        System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
        return encoding.GetString(arr);
    }

    public static byte[] StrToByteArray(string str)
    {
        System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
        return encoding.GetBytes(str);
    }

It is a conversion issue because it works with non-converted strings.

EDIT 2:

public partial class Form1 : Form
{
    public volatile List<TcpClient> connectedClients;
    public volatile bool ServerOn;
    public volatile TcpListener server;
    public delegate void txtBoxDelegate(string data);
    public delegate void tcpCommand(string ipAddress);
    public delegate void chatMessageDelegate(byte[] message);

    public Form1()
    {
        InitializeComponent();
        connectedClients = new List<TcpClient>();
        ServerOn = false;
        server = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 6789);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (!ServerOn)
        {
            Thread serverThread = new Thread(new ThreadStart(TcpServer));
            serverThread.IsBackground = true;
            serverThread.Start();
            lblServerStatus.Text = "The server is On.";
            lblServerStatus.ForeColor = Color.Green;
            lstServerUpdates.Text = String.Empty;
            button1.Text = "Turn server Off";
            ServerOn = true;
        }
        else
        {
            ServerOn = false;
            lstServerUpdates.Text = "Server has been turned off.";
            lblServerStatus.Text = "The server is Off.";
            lblServerStatus.ForeColor = Color.Red;
        }
    }

    public static string ByteArrayToStr(byte[] arr)
    {
        System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
        return encoding.GetString(arr);
    }

    public static byte[] StrToByteArray(string str)
    {
        System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
        return encoding.GetBytes(str);
    }

    private void TcpServer()
    {
        printToTextBox("Starting TCP Server.");

        server.Start();
        while (ServerOn)
        {
            if (!server.Pending())
            {
                Thread.Sleep(10);
                continue;
            }
            TcpClient clientSocket = server.AcceptTcpClient();

            NetworkStream stream = clientSocket.GetStream();

            connectedClients.Add(clientSocket);

            Thread clientThread = new Thread(new ParameterizedThreadStart(ClientThreads));
            clientThread.Start(clientSocket);

            byte[] bytes = StrToByteArray("Successfully connected to the server.");

            stream.Write(bytes, 0, bytes.Length);
            printToTextBox("Client successfully connected to server.");
        }


        server.Stop();
    }

    public void ClientThreads(object tcpClient)
    {
        TcpClient clientSocket = (TcpClient)tcpClient;
        NetworkStream clientStream = clientSocket.GetStream();

        byte[] clientMessage = new byte[100];

        while (ServerOn)
        {
            clientStream.Read(clientMessage, 0, clientMessage.Length);
            string message = ByteArrayToStr(clientMessage);
            if (message.Contains("!chat"))
            {
                SendChatMessage(StrToByteArray(message.Substring(5) + Environment.NewLine));
            }
            else if (message.Contains("!start")) 
            {
                StartWebcam(((IPEndPoint)clientSocket.Client.RemoteEndPoint).Address.ToString());
            }
            else if (message.Contains("!stop"))
            {
                StopWebcam(((IPEndPoint)clientSocket.Client.RemoteEndPoint).Address.ToString());
            }
        }
        clientSocket.Close();
        connectedClients.Clear();
    }

    public void printToTextBox(string data)
    {
        if (this.InvokeRequired)
        {
            this.BeginInvoke(new txtBoxDelegate(printToTextBox), data);
            return;
        }
        lstServerUpdates.Text += data + Environment.NewLine;
    }

    public void SendChatMessage(byte[] message)
    {
        foreach (TcpClient client in connectedClients)
        {
            NetworkStream stream = client.GetStream();
            stream.Write(message, 0, message.Length);
            printToTextBox(ByteArrayToStr(message));
        }
    }

    public void StartWebcam(string IPAddress)
    {
        if (this.InvokeRequired)
        {
            this.BeginInvoke(new tcpCommand(StartWebcam), IPAddress);
            return;
        }

        //code to stop webcam for the specified client
        printToTextBox("Starting webcam for IP: " + IPAddress);
    }

    public void StopWebcam(string IPAddress)
    {
        if (this.InvokeRequired)
        {
            this.BeginInvoke(new tcpCommand(StopWebcam), IPAddress);
            return;
        }

        //code to stop webcam for specified client
        printToTextBox("Stopping webcam for IP: " + IPAddress);
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T05:12:30+00:00Added an answer on June 14, 2026 at 5:12 am

    I send a stream of bytes

    That’s correct, TCP is a stream. Which doesn’t support anything like a “packet”. Like a line of text. There’s no obvious way to convert a stream to byte[], other than to receive everything until the client closes the connection. Which of course means that you’ll display everything, followed by a single Environment.NewLine.

    Rethink your approach. Like actually sending the line-endings in the data as well so you don’t have to add them in the receiver. Artificially creating packets by first sending 4 bytes that encodes the packet length is another approach.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I am reading a book about Javascript and jQuery and using one of the
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
We are using XSLT to translate a RIXML file to XML. Our RIXML contains
I need a function that will clean a strings' special characters. I do NOT
I want to construct a data frame in an Rcpp function, but when I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.