我在C ++和C#之间进行了简单的客户端/服务器通信,其中C#程序将字符串发送到C ++。
字符串的发送分三个阶段进行。发送字符串长度的长度->发送字符串长度->发送字符串。
出于调试目的,我在C#程序上有一个名为textbox1的TextBox要打印
对于三个已发送的值,使用textbox1.AppendText()发送了三个值。
一切都已正确发送和接收,当我从代码中删除三个AppendText()行中的两个时,它仍然可以工作,但是奇怪的是,当我删除了第三行时(注释为//<--This Line
,C ++服务器收到0!
C#客户端(代码段):
private void button1_Click(object sender, EventArgs e)
{
try
{
MemoryStream ms;
NetworkStream ns;
TcpClient client;
BinaryWriter br;
byte[] tosend;
string AndroidId = "2468101214161820";
string len = AndroidId.Length.ToString();
string lol = len.Length.ToString();
ms = new MemoryStream();
client = new TcpClient("127.0.0.1", 8888);
ns = client.GetStream();
br = new BinaryWriter(ns);
//****************Send Length Of Length***************
tosend = System.Text.Encoding.ASCII.GetBytes(lol);
br.Write(tosend);
textBox1.AppendText(Encoding.ASCII.GetString(tosend));//<---THIS LINE
//****************Send Length***************
tosend = System.Text.Encoding.ASCII.GetBytes(len);
br.Write(tosend);
//****************Send Length Of Length***************
tosend = System.Text.Encoding.ASCII.GetBytes(AndroidId);
br.Write(tosend);
ns.Close();
client.Close();
}
C ++服务器代码段:
//***********Recieve Length Of Length*****************
char* lol_buff0 = new char[1];
int nullpoint= recv(s, lol_buff0, strlen(lol_buff0), 0);
lol_buff0[nullpoint] = '\0';
int lengthoflength = atoi(lol_buff0);
//***********Recieve Length*****************
char* l_buff0 = new char[lengthoflength];
int nullpoint2=recv(s, l_buff0, strlen(l_buff0), 0);
l_buff0[nullpoint2] = '\0';
int length = atoi(l_buff0);
//***********Recieve AndroidID*****************
char* AndroidID = new char[length];
valread0 = recv(s, AndroidID, strlen(AndroidID), 0);
if (valread0 == SOCKET_ERROR)
{
int error_code = WSAGetLastError();
if (error_code == WSAECONNRESET)
{
//Somebody disconnected , get his details and print
printf("Host disconnected unexpectedly , ip %s , port %d \n", inet_ntoa(address.sin_addr), ntohs(address.sin_port));
//Close the socket and mark as 0 in list for reuse
closesocket(s);
client_socket[i] = 0;
}
else
{
printf("recv failed with error code : %d", error_code);
}
}
if (valread0 == 0)
{
//Somebody disconnected , get his details and print
printf("Host disconnected , ip %s , port %d \n", inet_ntoa(address.sin_addr), ntohs(address.sin_port));
//Close the socket and mark as 0 in list for reuse
closesocket(s);
client_socket[i] = 0;
}
else
{
//add null character, if you want to use with printf/puts or other string handling functions
AndroidID[valread0] = '\0';
printf("%s:%d Your Android ID is - %s \n", inet_ntoa(address.sin_addr), ntohs(address.sin_port), AndroidID);
}
我知道只要它可以工作,我就可以容纳它,但是它太奇怪了,我想知道对此的解释是什么。谢谢。
最佳答案
您假设将在一个recv
调用中接收数据(或者,一个发送对应一个接收)。这是一个错误的假设。您需要继续读取,直到读取数据字节的长度。 TCP没有内置的任何消息传递,它仅处理流。
添加线路可能意味着添加了一些小的延迟,从而使接收在单个调用中发生-很难说,因为您要处理的不确定性很高。正确处理TCP,然后查看问题是否仍然存在。
关于c# - 为什么从我的代码中删除TextBox.AppendText()更改此处的套接字通信?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37875787/