这里是源代码,我无法理解会发生什么。当我从服务器接收数据然后回写到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();
}
}
答案 0 :(得分:0)
这是一个服务器端问题所以这段代码没问题。 服务器从未收到值-1,因此没有回复。