为什么在更改源代码后服务器停止响应?

Why has the server stopped responding after a change in source code?

我需要通过TCP实现HTTP协议。我已经有了一个运行良好的 TCP/IP 客户端-服务器程序。

现在,我对源代码做了一些小改动,使其表现得像 an HTTP client-server。但是,不幸的是它停止工作了。

下面的代码...

    public void Write(string str)
    {
        if (IsConnected)
        {
            byte[] strBytes = Encoding.UTF8.GetBytes(str);
            byte[] lenBytes = BitConverter.GetBytes(strBytes.Length);
            Array.Reverse(lenBytes);
            writer.Write(lenBytes);
            writer.Write(strBytes);
            writer.Flush();
        }
        else
        {
            throw new Exception("Client " + ID + " is not connected!");
        }
    }

    public string Read()
    {
        if (IsConnected)
        {
            byte[] lenBytes = reader.ReadBytes(4);
            Array.Reverse(lenBytes);
            int len = BitConverter.ToInt32(lenBytes, 0);
            byte[] bytes = reader.ReadBytes(len);
            string str = Encoding.UTF8.GetString(bytes);

            return str;
        }
        else
        {
            throw new Exception("Client " + ID + " is not connected!");
        }
    }

更改为:

    public void Write(string str)
    {
        if (IsConnected)
        {
            byte[] send = Encoding.ASCII.GetBytes(str);
            writer.Write(send);
            writer.Flush();
        }
        else
        {
            throw new Exception("Client " + ID + " is not connected!");
        }
    }

    public string Read()
    {
        if (IsConnected)
        {
            StreamReader sr = new StreamReader(stream);
            string str = sr.ReadToEnd();

            return str;
        }
        else
        {
            throw new Exception("Client " + ID + " is not connected!");
        }
    }

这是什么问题?


详细源代码

以下class服务器程序和客户端程序都使用

修改:

namespace MyClientServer
{
    public class ClientClass
    {
        private string Host { get; set; }
        private int Port { get; set; }

        private bool IsConnected = false;

        public string ID { get; private set; }
        public TcpClient Tcp { get; private set; }

        NetworkStream stream;
        private StreamReader sr;
        private StreamWriter writer;

        public ClientClass()
        {
            Random rnd = new Random();
            ID = AlphaNumRandom.GenerateUpperCaseString(5, rnd);
        }

        //constructor for server program.
        public ClientClass(TcpListener listener)
        {
            Tcp = listener.AcceptTcpClient();

            Host = ((IPEndPoint)Tcp.Client.RemoteEndPoint).Address.ToString();
            Port = ((IPEndPoint)Tcp.Client.LocalEndPoint).Port;

            IsConnected = true;

            stream = Tcp.GetStream();
            sr = new StreamReader(stream);
            writer = new StreamWriter(stream);

            ID = Read();

            Console.WriteLine("Client [{0}] is now connected.", ID);

        }

        public bool Connect()
        {
            if (IsConnected == false)
            {
                Console.WriteLine("Client [{0}] is now connected.", ID);

                IsConnected = true;

                Tcp = new TcpClient(Host, Port);

                stream = Tcp.GetStream();
                sr = new StreamReader(stream);
                writer = new StreamWriter(stream);

                return true;
            }

            return false;
        }

        //constructor for client.
        public ClientClass(string host, int port)
        {
            Random rnd = new Random();
            ID = AlphaNumRandom.GenerateUpperCaseString(5, rnd);
            Host = host;
            Port = port;
        }

        public void Write(string str)
        {
            if (IsConnected)
            {
                byte[] send = Encoding.ASCII.GetBytes(str);
                writer.Write(send);
                writer.Flush();
            }
            else
            {
                throw new Exception("Client " + ID + " is not connected!");
            }
        }

        public string Read()
        {
            if (IsConnected)
            {
                StreamReader sr = new StreamReader(stream);
                string str = sr.ReadToEnd();

                return str;
            }
            else
            {
                throw new Exception("Client " + ID + " is not connected!");
            }
        }

        public void PrintID()
        {
            Console.WriteLine("Client ID = {0}", ID);
        }

        public void SendIdToServer()
        {
            this.Write(ID);
        }

        public bool Disconnect()
        {
            if (IsConnected)
            {
                if (Tcp != null)
                {
                    Tcp.Close();
                    Tcp = null;

                    Console.WriteLine("\nClient [{0}] is now disconnected.", ID);

                    return true;
                }
            }

            return false;
        }        
    }
}

原文:

namespace MyClientServer
{
    public class ClientClass
    {
        private string Host { get; set; }
        private int Port { get; set; }

        private bool IsConnected = false;

        public string ID { get; private set; }
        public TcpClient Tcp { get; private set; }

        private BinaryReader reader;
        private BinaryWriter writer;

        public ClientClass()
        {
            Random rnd = new Random();
            ID = AlphaNumRandom.GenerateUpperCaseString(5, rnd);
        }

        //constructor for server program.
        public ClientClass(TcpListener listener)
        {
            Tcp  = listener.AcceptTcpClient();

            Host = ((IPEndPoint)Tcp.Client.RemoteEndPoint).Address.ToString();
            Port = ((IPEndPoint)Tcp.Client.LocalEndPoint).Port;

            IsConnected = true;

            NetworkStream stream = Tcp.GetStream();
            reader = new BinaryReader(stream);
            writer = new BinaryWriter(stream);

            ID = Read();

            Console.WriteLine("Client [{0}] is now connected.", ID);

        }

        public bool Connect()
        {
            if (IsConnected == false)
            {
                Console.WriteLine("Client [{0}] is now connected.", ID);

                IsConnected = true;

                Tcp = new TcpClient(Host, Port);

                NetworkStream stream = Tcp.GetStream();
                reader = new BinaryReader(stream);
                writer = new BinaryWriter(stream);

                return true;
            }

            return false;
        }

        //constructor for client.
        public ClientClass(string host, int port)
        {
            Random rnd = new Random();
            ID = AlphaNumRandom.GenerateUpperCaseString(5, rnd);
            Host = host;
            Port = port;
        }

        public void Write(string str)
        {
            if (IsConnected)
            {
                byte[] strBytes = Encoding.UTF8.GetBytes(str);
                byte[] lenBytes = BitConverter.GetBytes(strBytes.Length);
                Array.Reverse(lenBytes);
                writer.Write(lenBytes);
                writer.Write(strBytes);
                writer.Flush();
            }
            else
            {
                throw new Exception("Client " + ID + " is not connected!");
            }
        }

        public string Read()
        {
            if (IsConnected)
            {
                byte[] lenBytes = reader.ReadBytes(4);
                Array.Reverse(lenBytes);
                int len = BitConverter.ToInt32(lenBytes, 0);
                byte[] bytes = reader.ReadBytes(len);
                string str = Encoding.UTF8.GetString(bytes);

                return str;
            }
            else
            {
                throw new Exception("Client " + ID + " is not connected!");
            }
        }

        public void PrintID()
        {
            Console.WriteLine("Client ID = {0}", ID);
        }

        public void SendIdToServer()
        {
            this.Write(ID);
        }

        public bool Disconnect()
        {
            if (IsConnected)
            {
                if (Tcp != null)
                {
                    Tcp.Close();
                    Tcp = null;

                    Console.WriteLine("\nClient [{0}] is now disconnected.", ID);

                    return true;
                }
            }

            return false;
        }
    }
}

我听取了@Jimi的建议,还看了this link的源代码。

现在我的源代码如下所示:

    public string Read()
    {
        if (IsConnected)
        {
            byte[] buffer = new byte[Tcp.ReceiveBufferSize];//create a byte array
            int bytesRead = stream.Read(buffer, 0, Tcp.ReceiveBufferSize);//read count
            string str = Encoding.ASCII.GetString(buffer, 0, bytesRead);//convert to string
            return str;
        }
        else
        {
            throw new Exception("Client " + ID + " is not connected!");
        }
    }

    public void Write(string str)
    {
        if (IsConnected)
        {
            byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(str);
            stream.Write(bytesToSend, 0, bytesToSend.Length);
            stream.Flush();
        }
        else
        {
            throw new Exception("Client " + ID + " is not connected!");
        }
    }

而且,它工作正常。