简体   繁体   English

通过tcplistener发送对象

[英]Send objects through tcplistener

Are there any ways to send anything besides strings through a tcplistener? 除了通过字符串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. [编辑]如果这是一个愚蠢的问题,我深表歉意,但我想在此处了解有关联网的更多信息。

Depends, if you can attach say BinaryWriter to the NetworkStream , then you can do stuff like: 取决于,如果您可以将BinaryWriter附加到NetworkStream ,则可以执行以下操作:

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 (eg, endianness is fixed). 但是我认为BinaryReaderBinaryWriter为您处理这些问题(例如,字节序是固定的)。

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. Just BinaryWriter在这里是一个抽象,它为您完成了将整数转换为字节数组的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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