Jean Bobo
Jean Bobo

Reputation: 17

How to send back a byte in socket

I want to send a string converted in byte but i don't know how to do that. I already tried to modify buffer and byteread but the server is just broken.

    private void Server(string ip, int port)
    {
        BackgroundWorker worker = new BackgroundWorker();
        worker.DoWork += delegate (object s, DoWorkEventArgs args)
        {
            //---listen at the specified IP and port no.---
            IPAddress localAdd = IPAddress.Parse(ip);
            TcpListener listener = new TcpListener(localAdd, port);
            Console.WriteLine("Listening...");
            listener.Start();

        while (true)
        {
            //---incoming client connected---
            TcpClient client = listener.AcceptTcpClient();

            //---get the incoming data through a network stream---
            NetworkStream nwStream = client.GetStream();
            byte[] buffer = new byte[client.ReceiveBufferSize];

            //---read incoming stream---
            int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);

            //---convert the data received into a string---
            string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
            Console.WriteLine("Received : " + dataReceived);


            //---write back the text to the client---
            Console.WriteLine("Sending back : " + dataReceived);
            nwStream.Write(buffer, 0, bytesRead); // How do i send back a string ??
            client.Close();
        }
        };
        worker.RunWorkerAsync();
    }

Upvotes: 1

Views: 197

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063338

You already are sending back the bytes that represent the same string (via ASCII) that you received in the first Read, then closing the socket. Note: if you intended to send back the bytes for a different string value: Encoding.ASCII or Encoding.Utf8 are your friends; the process of converting between string data and byte data (for transmission or storage) is exactly what an Encoding does. You're already using this with GetString(...); the reverse operation is GetBytes(...) (with various overloads for using pooled buffers etc).

If this isn't working as intended, we'd need a lot more detail. In particular, TCP is a stream protocol; data isn't terminated inherently (like it would be in UDP packets, for example), so there is no guarantee whatsoever that you've received a logical unit of string data in your Read - all we know is that one Read has completed. This could return zero bytes (indicating EOF, i.e. the other end didn't send anything and closed their outbound socket), one byte, or a few thousand bytes - but: except for the EOF case, that tells us nothing about whether we have an entire "message". In fact, if you were using UTF8 rather than ASCII, we might not even have an entire character - we could have partial/incomplete character data.

So if the "other end" is trying to send us a paragraph of data, we might have received the first word-and-a-half; you then send back the same word-and-a-half, and terminate the connection. We have never seen the rest of the data. Whether this is what you want is unclear, but seems unlikely. That's assuming this actually is a text-based protocol!

For this reason, usually any network protocol includes framing details to tell us how to identify logical units of data in the stream. For a text protocol this might be looking for sentinel characters like CR/LF/NUL; for a binary protocol, this usually takes the form of some header that tells us the number of bytes in the data frame in a well-defined format ("big endian int32", "varint", etc), followed by that same number of bytes. The caller then buffers appropriately so that they're processing only entire frames.

So: in theory you're already sending something back (unless it was EOF), but without the protocol details: we can't say whether than means anything.

Upvotes: 1

Related Questions