Solved

How to read from a networkstream?

Posted on 2004-07-30
13
443 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
Are your AD admin tools letting you down?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

 
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
 
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

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

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

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
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…
In a recent question (https://www.experts-exchange.com/questions/28997919/Pagination-in-Adobe-Acrobat.html) here at Experts Exchange, a member asked how to add page numbers to a PDF file using Adobe Acrobat XI Pro. This short video Micro Tutorial sh…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

770 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