开发者

c# http response

开发者 https://www.devze.com 2022-12-19 15:41 出处:网络
I am trying to learn and writting this part of code. while testing few weeks before it ran the way i wanted, it does not work its code from msdn and the http response part was being suggested byferoz

I am trying to learn and writting this part of code.

while testing few weeks before it ran the way i wanted, it does not work its code from msdn and the http response part was being suggested by feroz Using HttpWebRequest to send HTML to a Browser

now after a while it does not work..

i was expecting to get hello there message as in code which could be by using (StreamWriter sw = new StreamWriter(stream)) { sw.Write("<html><body>Hello There!</body></html>"); } but it only shows GET\

     try
     {

        // Set the TcpListener on port 13000.
            Int32 port = 80;
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");

            // TcpListener server = new TcpListener(port);
            TcpListener server = new TcpListener(localAddr, port);

            // Start listening for client requests.
            server.Start();

            // Buffer for reading data
            Byte[] bytes = new Byte[256];
            String data = null;

            // Enter the listening loop.
            while (true)
            {
                Console.Write("Waiting for a connection... ");

                // Perform a blocking call to accept requests.
                // You could also user server.AcceptSocket() here.
                TcpClient client = server.AcceptTcpClient();
                Console.WriteLine("Connected!");

                data = null;

                // Get a stream object for reading and writing
                NetworkStream stream = client.GetStream();

                int i;

                // Loop to receive all the data sent by the client.
                while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                {
                    // Translate data bytes to a ASCII string.
                    data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                    Console.WriteLine(String.Format("Received: {0}", data));

                    // Process the data sent by the client.
                    data = data.ToUpper();

                    byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

                    // Send back a response.
                    stream.Write(msg, 0, msg.Length);
                    Console.WriteLine("Sending message..");


    using(StreamWriter sw = new StreamWriter(stream))
    {
        sw.Write("<html><body>Hello There!</body></html>");
    }

                 }

                // Shutdown and end connec开发者_开发百科tion
                client.Close();
            }
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }

        Console.WriteLine("\nHit enter to continue...");
        Console.Read();
    }
}


The code presented in the question will throw ObjectDisposedException after the first read from the network. What you are doing “wrong” is disposing the StreamWriter (implicit in the using statement), which disposes the underlying network stream. Once disposed, you cannot go back and read from it anymore. Additionally, you are mixing writing directly to the stream and writing through the (buffered) StreamWriter.

The question should be re-phrased to something like:

**

Why does this code read/write data from a client once, then throw an exception on the second read attempt?

**

I would restructure the code as shown below. [Note: The Flush() call is not really needed, but you probably want it in there for this demo.]

try
{
    // Listen for connections on port 13000
    TcpListener server = new TcpListener(IPAddress.Loopback, 13000);
    server.Start();

    // Read up tp 256 bytes at a time 
    Byte[] bytes = new Byte[256];
    String data;

    // Enter the listening loop. 
    while (true)
    {
        Console.WriteLine("Waiting for a connection... ");

        // Wait for a client connection
        TcpClient client = server.AcceptTcpClient();
        Console.WriteLine("Connected!");

        // Setup I/O streams
        NetworkStream stream = client.GetStream();
        using (StreamWriter sw = new StreamWriter(stream))
        {
            int i;

            // Loop to receive all the data sent by the client. 
            while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
            {
                // Translate data bytes to a ASCII string. 
                data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                Console.WriteLine(String.Format("Received: {0}", data));

                // Process the data sent by the client. 
                data = data.ToUpper();

                // Send back a response. 
                Console.WriteLine("Sending message..");
                sw.Write(data);

                // Add a little extra 'response'
                sw.Write("<html><body>Hello There!</body></html>");
                sw.Flush();
            }
        }
        // Close connection 
        client.Close();
    }
}
catch (SocketException e)
{
    Console.WriteLine("SocketException: {0}", e);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消