Solved

How to read from a networkstream?

Posted on 2004-07-30
13
433 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
  • 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
 
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 500 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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Bit flags and bit flag manipulation is perhaps one of the most underrated strategies in programming, likely because most programmers developing in high-level languages rely too much on the high-level features, and forget about the low-level ones. Th…
Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
This video discusses moving either the default database or any database to a new volume.

707 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now