C# and NetworkStream, sending is ok but receiving is not working

試著忘記壹切 提交于 2020-01-07 08:31:46

问题


here is the source code, I can't understand what happens. When I receive data from server then writes back to the NetworkStream then it works but when I try to send first before reading from the server it does not work :

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:


This was a server side issue so this code is ok. The server was never receiving the value -1 so it did not reply back.



来源:https://stackoverflow.com/questions/33841741/c-sharp-and-networkstream-sending-is-ok-but-receiving-is-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!