C#和NetworkStream,发送可以,但接收不起作用
本文关键字:不起作用 NetworkStream | 更新日期: 2023-09-27 18:23:40
这是源代码,我不明白发生了什么。当我从服务器接收数据,然后写回NetworkStream时,它就工作了,但当我试图在从服务器读取之前先发送时,它不工作:
void BtnConnectClick(object sender, EventArgs e)
{
TcpClient clientSocket = null;
NetworkStream networkStream = null;
try{
clientSocket = new TcpClient();
clientSocket.SendTimeout = 5000;
clientSocket.ReceiveTimeout = 5000;
clientSocket.Connect("192.168.0.13",7777);
networkStream = clientSocket.GetStream();
const string strToAndroid = "hi from client";
char[] carray = strToAndroid.ToCharArray();
for (int i=0;i<carray.GetLength(0);i++)
{
networkStream.WriteByte((byte)carray[i]);
}
log("sent to Android = " + strToAndroid);
string strFromAndroid = "";
int j=0;
while (j!=-1)
{
try
{
j = networkStream.ReadByte();
if (j!=-1)
strFromAndroid += (char)j;
}
catch(Exception ex){
break;
}
}
log("received from Android = " + strFromAndroid);
networkStream.Close();
clientSocket.Close();
}
catch(Exception ex){
log("002:" + ex.Message);
if (networkStream != null)
networkStream.Close();
if (clientSocket != null)
clientSocket.Close();
}
}
这是服务器端的问题,因此此代码可以。服务器从未接收到值-1,因此没有回复。