-4

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 connection
                client.Close();
            }
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }

        Console.WriteLine("\nHit enter to continue...");
        Console.Read();
    }
}
6
  • 9
    How does it "not work" ? What's happening ? Any exceptions ? What kind of client are you using to connect to this server ? Commented Feb 10, 2010 at 16:37
  • Why doesn't it work? What happens? Do you have a firewall? Commented Feb 10, 2010 at 16:38
  • What is the error you are getting? Commented Feb 10, 2010 at 16:40
  • no exception just doesnot work like the progress bar keep on showing Commented Feb 10, 2010 at 16:42
  • 2
    You need a few more question marks. Commented Feb 10, 2010 at 16:43

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for your support .... but the issue is still my browser could not display the message "Hello There" back... may be bcoz there is no http header response but no clue how that can be done.... to sum up i wanted my browser to display that html tags..
If you want your browser to display a message, then you have to use the HTTP protocol for communications, not just send back some HTML. See documentation on the HTTP protocol on the web; it is not hard to write a web server, search the internet for how to accomplish.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.