Tech or Treat! Write an article about your scariest tech disaster to win gadgets!Learn more

x
?
Solved

How to read from a networkstream?

Posted on 2004-07-30
13
Medium Priority
?
466 Views
Last Modified: 2010-04-15
Ola,

In the method GetHTTPrequest I want to write to the concole the text in the stream from the request that came in on the tcp listner.
How do I do that?

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections;

namespace AtomHTTPresponse
{
      class AtomHTTPresponse
      {
            private byte[] cByteSteamData = null;
            static void Main(string[] args)
            {
                  AtomHTTPresponse lObjAtomHTTPresponse = new AtomHTTPresponse();
                  TcpListener lObjTcpListner = new TcpListener( 9999 );
                  lObjTcpListner.Start();
                  Console.WriteLine( "Listening started" );
                  TcpClient lObjTcpClient = lObjTcpListner.AcceptTcpClient();
                  Console.WriteLine( "Got a client" );
                  NetworkStream lObjNetworkStream = lObjTcpClient.GetStream();
                  lObjNetworkStream.BeginRead( lObjAtomHTTPresponse.cByteSteamData, 0, 1048576, new AsyncCallback( lObjAtomHTTPresponse.GetHTTPrequest ), null );
            }
            private void GetHTTPrequest( IAsyncResult ar )
            {
                  //Console.WriteLine( "Here I want the HTTP request written" );
            }
            private void RespondHTTP()
            {
                  /*
                  string lStrHTTPheader = "";
                  lStrHTTPheader += "HTTP/1.1 404\r\n";
                  lStrHTTPheader += "Server: c# DHTML Chat Server V0.01alpha\r\n";
                  lStrHTTPheader += "Content-Type: text/html\r\n";
                  lStrHTTPheader += "Accept-Ranges: bytes\r\n";
                  lStrHTTPheader += "Content-Length: 1000000000000000\r\n\r\n"; // Igone this HTTP header for now. We will get to that subject in another question
               
                  Byte[] lArrBtHTTPheader = System.Text.Encoding.ASCII.GetBytes( lStrHTTPheader );
                  
                  lObjNetworkStream.Write( lArrBtHTTPheader, 0, lArrBtHTTPheader.Length );
                  Console.WriteLine( "HTTP header send" );
                  string lStrHTTPcontent = "";
                  lStrHTTPheader += "<html><head><title>yoyo</title></head><body>ohh yeah</body></html>";
               
                  Byte[] lArrBtHTTPcontent = System.Text.Encoding.ASCII.GetBytes( lStrHTTPcontent );

                  lObjNetworkStream.Write( lArrBtHTTPcontent, 0, lArrBtHTTPcontent.Length );
                  Console.WriteLine( "HTTP content send" );
                  */
            }
      }
}
0
Comment
Question by:DaFou
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 5
13 Comments
 
LVL 3

Expert Comment

by:dukkorg
ID: 11679529
You could try:

Console.Write(System.Text.Encoding.ASCII.GetString(lObjAtomHTTPresponse.cByteSteamData));
0
 
LVL 2

Author Comment

by:DaFou
ID: 11680781
Compile error
The type or namespace name 'lObjAtomHTTPresponse' could not be found (are you missing a using directive or an assembly reference?)

Console.Write(System.Text.Encoding.ASCII.GetString(      !! lObjAtomHTTPresponse !!     .cByteSteamData));
0
 
LVL 3

Expert Comment

by:dukkorg
ID: 11681592
Sorry My bad. Just do:

Console.Write(System.Text.Encoding.ASCII.GetString(cByteSteamData));
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 2

Author Comment

by:DaFou
ID: 11681735
This code:
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections;

namespace AtomHTTPresponse
{
      class AtomHTTPresponse
      {
            private byte[] cByteStreamData = new byte[1048576];
            static void Main(string[] args)
            {
                  AtomHTTPresponse lObjAtomHTTPresponse = new AtomHTTPresponse();
                  TcpListener lObjTcpListner = new TcpListener( 9999 );
                  lObjTcpListner.Start();
                  Console.WriteLine( "Listening started" );
                  TcpClient lObjTcpClient = lObjTcpListner.AcceptTcpClient();
                  Console.WriteLine( "Got a client" );
                  NetworkStream lObjNetworkStream = lObjTcpClient.GetStream();
                  lObjNetworkStream.BeginRead( lObjAtomHTTPresponse.cByteStreamData, 0, 1048576, new AsyncCallback( lObjAtomHTTPresponse.GetHTTPrequest ), null );
            }
            private void GetHTTPrequest( IAsyncResult ar )
            {
                  //Console.WriteLine( "Here I want the HTTP request written" );
                  Console.WriteLine(System.Text.Encoding.ASCII.GetString(cByteStreamData));
            }
      }
}

Renders this result:

C:\_data\Projects\AtomHTTPresponse\bin\Debug>AtomHTTPresponse.exe
Listening started
Got a client

C:\_data\Projects\AtomHTTPresponse\bin\Debug>

THe HTTP request is not being displayed when i connect to my localhost on port 9999 with my browser
0
 
LVL 3

Accepted Solution

by:
dukkorg earned 2000 total points
ID: 11682064
Ok I made a version that does what your looking for (I Think):

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections;
using System.IO;

namespace AtomHTTPresponse
{
      internal sealed class AtomHTTPresponse
      {
            private static Server server = null;

            private static void Main(string[] args)
            {
                  server = new Server( 9999 );
                  server.Start();

                  // You'll probably want to stop sometime...
            }
      }

      internal class Server
      {
            private TcpListener tcpListner = null;
            private bool keepRunning = false;

            public Server(int port)
            {
                  tcpListner = new TcpListener(port);
            }

            public void Start()
            {
                  keepRunning = true;

                  tcpListner.Start();
                  Console.WriteLine("Listening started");
                  
                  while (keepRunning)
                  {
                        ThreadPool.QueueUserWorkItem(new WaitCallback(processRequest), tcpListner.AcceptTcpClient());
                  }
            }

            public void Stop()
            {
                  keepRunning = false;
                  tcpListner.Stop();
                  Console.WriteLine("Listening stopped");
            }

            private void processRequest(object state)
            {
                  Console.WriteLine("Got a Client");
                  TcpClient tcp = state as TcpClient;

                  if (tcp != null)
                  {
                        NetworkStream stream = tcp.GetStream();
                        StreamReader reader = new StreamReader(stream);
                        StreamWriter writer = new StreamWriter(stream);
      
                        while (reader.Peek() >= 0)
                        {
                              char[] c = new char[256];
                              reader.Read(c, 0, c.Length);
                              Console.Write(c);
                        }

                        // TODO: Send something back...
                        writer.Write("HTTP Header... Content...");
                        writer.Flush();

                        Console.WriteLine("Response Sent");

                        // TODO: Check for keep-alive if you want to follow the RFC etc...

                        stream.Close();
                        tcp.Close();

                        Console.WriteLine("Client Session Ended.");
                  }
                  else
                  {
                        Console.WriteLine("Bad Client, Ignoring request.");
                  }
            }
      }
}
0
 
LVL 2

Author Comment

by:DaFou
ID: 11683095
Can you please help me out with the folow up to this question on how to minimize this code?
It is quite large now using threadpool and other stuff I really dont want to use YET.

Please partisipate in my next question about this:
http://www.experts-exchange.com/Programming/Programming_Languages/C_Sharp/Q_21077813.html

Regards
0
 
LVL 2

Author Comment

by:DaFou
ID: 11683100
like do all your magic in GetHTTPrequest would be of great help. plain and simple straigt forward.
It will help my learning process of the C# and the networking

Regards
0
 
LVL 3

Expert Comment

by:dukkorg
ID: 11683122
Well you deleted your new post right before I posted. So I guess I'll still be nice and post it here:

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace AtomHTTPresponse
{
      internal sealed class SimpleHttp
      {
            private static void Main(string[] args)
            {
                  TcpListener tcpListner = new TcpListener(9999);
                  tcpListner.Start();
                  Console.WriteLine("Listening started.");

                  TcpClient tcp = tcpListner.AcceptTcpClient();

                  Console.WriteLine("Starting new session.");
                  NetworkStream stream = tcp.GetStream();
                  StreamReader reader = new StreamReader(stream);
                  StreamWriter writer = new StreamWriter(stream);

                  Console.WriteLine("Reading request.");
                  char[] chars = new char[256];
                  reader.Read(chars, 0, chars.Length);
                  Console.Write(chars);

                  Console.WriteLine("Building Response.");
                  string content = "<html><head><title>Response</title></head><body>Here's a response.</body></html>";
                  string header = "HTTP/1.1 200 OK\r\n"
                        + "Cache-Control: private\r\n"
                        + "Content-Type: text/html\r\n"
                        + "Server: SimpleHttp/1.0\r\n"
                        + "Content-Length: " + Encoding.UTF8.GetByteCount(content) + "\r\n"
                        + "Date: " + DateTime.Now.ToLongTimeString() + "\r\n\r\n";
                  
                  Console.WriteLine("Sending response.");
                  writer.Write(header);
                  writer.Write(content);
                  writer.Flush();

                  Console.WriteLine("Cleaning up session.");
                  reader.Close();
                  writer.Close();
                  stream.Close();
                  tcp.Close();

                  Console.WriteLine("Press any key to quit.");
                  Console.Read();
            }
      }
}
0
 
LVL 2

Author Comment

by:DaFou
ID: 11683124
I apologise.

I already figurted it out:

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections;
using System.IO;

namespace AtomHTTPresponse
{
      class AtomHTTPresponse
      {
            private byte[] cByteStreamData = new byte[1048576];
            static void Main(string[] args)
            {
                  AtomHTTPresponse lObjAtomHTTPresponse = new AtomHTTPresponse();
                  TcpListener lObjTcpListner = new TcpListener( 9999 );
                  lObjTcpListner.Start();
                  Console.WriteLine( "Listening started" );
                  TcpClient lObjTcpClient = lObjTcpListner.AcceptTcpClient();
                  Console.WriteLine( "Got a client" );
                  NetworkStream lObjNetworkStream = lObjTcpClient.GetStream();
                  
                  StreamReader reader = new StreamReader( lObjNetworkStream );

                  while (reader.Peek() >= 0)
                  {
                        char[] c = new char[256];
                        reader.Read(c, 0, c.Length);
                        Console.Write(c);
                  }

            }
      }
}

This is as small as I can get it now.. from this basis Ill work further
0
 
LVL 2

Author Comment

by:DaFou
ID: 11683128
Sorry dukkorg,

that we crossed each other.

Ill be sure to keep posting in this thread the questions I open in folow up to my missions. TO enable you to earn maximum points as my missions progresses
0
 
LVL 3

Expert Comment

by:dukkorg
ID: 11683137
If you want a decent book on learning all of this you can pick this one up used from amazon for cheap. 9 used & new from $5.92

http://www.amazon.com/exec/obidos/ASIN/1861007353/qid%3D1091257973/sr%3D11-1/ref%3Dsr%5F11%5F1/104-4299452-5460711
0
 
LVL 2

Author Comment

by:DaFou
ID: 11683138
I want you to have the point you deserver. I insist you take them as you earned them.
To activity on my part I screwed up a bit.

Come get your points please:
http://www.experts-exchange.com/Programming/Programming_Languages/C_Sharp/Q_21077819.html
0
 
LVL 2

Author Comment

by:DaFou
ID: 11683229
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…

647 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question