问题描述
我已经建立了发送和接收数据来回,在Windows应用程序的两台计算机之间的TCP连接。那我送的信息是一组由转换成字符串和分裂整数,。因此,对于发送数据我会使用,
I have established a TCP connection between two computers for sending and receiving data back and forth, in a windows application. The message that I am sending is a set of integers converted to string and split by ",". So, for sending the data I'd use,
if (dataSend.Length > 0)
{
m_writer.WriteLine(dataSend);
m_writer.Flush();
}
其中dataSend是我在字符串的形式消息,m_writer是的StreamWriter。
不过,现在我想将它传送为在同一个网络连接的整数数组,但我无法找到任何东西。我看用的人很多字节数组,但我不明白怎么回事,在读取时,接收器会知道如何将字节分割成各自的整数。
where dataSend is my message in the form of string, and m_writer is a StreamWriter.
But, now I want to send it as an array of integers over the same network connection but I can't find anything for it. I see a lot of people using byte array but with that I don't understand how, at the time of reading, the receiver would know how to split the bytes into the respective integer.
我认识到,WriteLine方法允许诠释作为它的参数太多,但我怎么送一个数组?结果
用绳子很清楚,因为我可以分离的基础上的数据,等我知道,每个元素将结束。将分离的标准是整型数组什么?
I realize that the writeline method allows for Int as its parameter too, but how do I send an array?
With string it was clear because I could separate the data based on "," and so I knew where each element would end. What would the separation criteria be for integer array?
这将是很好,如果有人可以解释这样对我,因为我也是相当新的C#的网络方面。
跟进的问题:<一href=\"http://stackoverflow.com/questions/28560009/streamreader-does-not-stop-reading-c-sharp/28578036?noredirect=1#comment45487175_28578036\">StreamReader不停止阅读C#
It would be nice if someone would explain this to me, as I am also fairly new to the networks aspect of C#.
Follow up question: StreamReader does not stop reading C#
推荐答案
你问一个问题,几乎总是结束在使用某种形式的序列化和/或数据帧被回答。 IE浏览器。 我怎么发一些结构过线?
You're asking a question that will almost always end up being answered by using serialization and/or data framing in some form. Ie. "How do I send some structure over the wire?"
您可能要序列化 INT []
来使用串行如 XmlSerializer的或JSON.NET库。然后,您可以在反序列化的另一端。
You may want to serialize your int[]
to a string using a serializer such as XmlSerializer or the JSON.NET library. You can then deserialize on the other end.
int[] numbers = new [] { 0, 1, 2, 3};
XmlSerializer serializer = new XmlSerializer(typeof(int[]));
var myString = serializer.Serialize(numbers);
// Send your string over the wire
m_writer.WriteLine(myString);
m_writer.Flush();
// On the other end, deserialize the data
using(var memoryStream = new MemoryStream(data))
{
XmlSerializer serializer = new XmlSerializer(typeof(int[]));
var numbers = (int[])serializer.Deserialize(memoryStream);
}
这篇关于如何在C#中的TCP连接发送整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!