通过套接字发送价值和阅读reader.ReadInt32()的值的变化值 [英] Send a value by socket and read the value by reader.ReadInt32() changes value
问题描述
我想通过套接字来发送的值。所以我在我的项目有两个部分客户端
和服务器
I am trying to send a value by socket .So i have two parts in my project Client
and server
.
客户端
使用此代码发送一个值,服务器:
The client
sends a value to server using this code :
System.IO.BinaryWriter binaryWriter =
new System.IO.BinaryWriter(networkStream);
binaryWriter.Write(1);
binaryWriter.Write(2);
binaryWriter.Flush();
因此,在其他部分我需要阅读这两个值我的意思是 1
和 2
;
因此,在服务器部分我有这样的代码:
So in server part i have this code :
static void Listeners()
{
Socket socketForClient = tcpListener.AcceptSocket();
if (socketForClient.Connected)
{
NetworkStream networkStream = new NetworkStream(socketForClient);
while (true)
{
List<int> variables = new List<int>();
using (var reader = new BinaryReader(networkStream))
{
for (int i = 0; i < 2; i++)
{
int t = reader.ReadInt32();
variables.Add(t);
}
}
}
}
}
正如你可以看到我在的变量保存的值
列表。但它不工作。我的意思是在服务器部分我不能让值 1
和 2
和我的价值观是这样的:841757955
As you can see i hold the values in variables
list .but it doesn't work .i mean in server part i can't get the values 1
and 2
and my values is like this :841757955
最诚挚的问候。
推荐答案
据我可以从你的代码告诉,你作为一个字符串发送数据二进制格式,这将产生字节字符 1,2
。
As far as I can tell from your code, you are sending data as a string in binary format, this will yield bytes for the characters 1,2
.
在读取数据备份尝试获得Int32值。
When you read the data back you try to get Int32 values.
有两个选项:
读取和写入数据的字符串。
Read and write data as a string.
Client code:
binaryWriter.Write("1,2");
Server code:
string text = binaryReader.ReadString(); // "1,2"
或读取和写入数据为整数。
OR Read and write data as integers.
Client code:
binaryWriter.Write(10);
binaryWriter.Write(20);
Server code:
int value1 = binaryReader.ReadInt32(); //10
int value2 = binaryReader.ReadInt32(); //20
这篇关于通过套接字发送价值和阅读reader.ReadInt32()的值的变化值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!