1

Are there any ways to send anything besides strings through a tcplistener? Because all of the examples that I have seen so far involve encoding a string to an array of bytes, sending that through, and decoding it on the other side.

Encoding.ASCII.GetBytes("message");
//This is then sent as an array of bytes

What if I wanted to send a float through, or an int through, or something else? Would this involve 'converting' an object to an array of bytes and sending that over?

[Edit] I apologize if this is a stupid question, but I'm trying to learn more about networking here.

vhu
  • 11,219
  • 11
  • 35
  • 42
RubixDude
  • 13
  • 2
  • Have a look at the answer to this question: http://stackoverflow.com/questions/3609280/sending-and-receiving-data-over-a-network-using-tcpclient you will find an explanation with code examples on how to send data over TCP. – Robin Jul 15 '15 at 08:41
  • The examples also have shown you how to send bytes. How else could the result from GetBytes have been sent. – usr Jul 15 '15 at 11:31
  • 1
    as [Giorgi](http://stackoverflow.com/a/31428755/) mentions you need to sent it as bytes in the end. It's what the network protocol understands. For the basic convertion though, do note that there is a [BitConverter.GetBytes(float) method](https://msdn.microsoft.com/en-us/library/yhwsaf3w%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396) – Default Jul 15 '15 at 11:45

1 Answers1

1

Depends, if you can attach say BinaryWriter to the NetworkStream, then you can do stuff like:

static void ServerTask(object clnObj)
{
    TcpClient client = clnObj as TcpClient;

    BinaryWriter bw = new BinaryWriter(client.GetStream());

    int k =99;
    bw.Write(k);

    client.Close();
}

But when sending in binary you should be careful with things like endianness. Also with floats, important is encoding, it must be same on receiving and sending parts. But I think BinaryReader, BinaryWriter handle these for you (e.g., endianness is fixed).

In the end everything is being sent as array of bytes. Just BinaryWriter is an abstraction here, and it does the work for you for converting the integer to array of bytes.

Community
  • 1
  • 1
gmoniava
  • 18,228
  • 5
  • 33
  • 74