Hi,
I have been using several http server code examples from the web, include
one from msdn, and I can't seem to get a simple http server thread working.
I can connect the server successful using IE6 and following url: http://127.0.0.1:5050
But when I attempt a second connect the windows symbol in the upper right
corner of ie starts in motion and nothing happens it just sits there waiting
for a response. The code also behaves very strangely when I try to debug
it, it will jump out of the serverThread function in the middle of the
stream.read loop and not return any exceptions, I'm really lost on this one.
The code also really seems to stumble when I use IE's refresh button rather
than typing in the URL if you can believe it.
I have included the class in question below stripped to the bone. Any
feedback would be appreciated.
-----
using System;
using System.Net;
using System.Net.Sock ets;
using System.Text;
using System.Threadin g;
namespace httpserv
{
/// <summary>
/// Summary description for PeerNetServer.
/// </summary>
public class httpserv
{
TcpListener listener;
private int port = 5050;
private Thread serverThread;
public httpserv()
{
//
// TODO: Add constructor logic here
//
}
public void Start()
{
listener = new TcpListener(IPA ddress.Parse("1 27.0.0.1"), port);
serverThread = new Thread(new ThreadStart(Ser verThread));
listener.Start( );
serverThread.St art();
}
public void Stop()
{
listener.Stop() ;
serverThread.Ab ort();
}
private void ServerThread()
{
while(true)
{
TcpClient client = listener.Accept TcpClient();
NetworkStream stream = client.GetStrea m();
int bytesRead;
Byte[] buffer = new Byte[1024];
string request = "";
while((bytesRea d = stream.Read(buf fer, 0, buffer.Length)) != 0)
{
request = request + Encoding.ASCII. GetString(buffe r, 0, bytesRead);
}
string output = "HTTP/1.1 200 OK\r\n";
output = output + "Content-type: text/plain\r\n";
output = output + "Content-length: " + request.Length + "\r\n";
output = output + "\r\n";
output = output + request;
byte[] msg = System.Text.Enc oding.ASCII.Get Bytes(output);
stream.Write(ms g, 0, msg.Length);
//stream.Flush(); // Documentation claims it doesn't do anything at this
time but thought I'd try it anyway
client.Close();
}
}
}
}
-----
Thanks in advance,
Dave 6 2515
Dave wrote: Hi,
I have been using several http server code examples from the web, include one from msdn, and I can't seem to get a simple http server thread working. I can connect the server successful using IE6 and following url: http://127.0.0.1:5050 But when I attempt a second connect the windows symbol in the upper right corner of ie starts in motion and nothing happens it just sits there waiting for a response. The code also behaves very strangely when I try to debug it, it will jump out of the serverThread function in the middle of the stream.read loop and not return any exceptions, I'm really lost on this one. The code also really seems to stumble when I use IE's refresh button rather than typing in the URL if you can believe it.
I have included the class in question below stripped to the bone. Any feedback would be appreciated.
[...]
That's a singlethreaded implementation -- the main server thread should
spawn a new thread for each request accepted. Check out the Cassini web
server at www.asp.net.
Cheers,
--
Joerg Jooss jo*********@gmx .net
Thanks Joerg,
Cassini looks like it will be very helpful, it is definitely a more complete
package than any of the examples I have come across to date, but I'd still
like to understand why my simple example doesn't work as expected before
getting into more complex examples. Even though it is single threaded
shouldn't the listener make itself available again once it has finished
processing a request? I'd also like to try to understand why it is not
consistently serving up the first request.
Thanks,
Dave
"Joerg Jooss" <jo*********@gm x.net> wrote in message
news:uy******** *****@tk2msftng p13.phx.gbl... Dave wrote:
Hi,
I have been using several http server code examples from the web, include one from msdn, and I can't seem to get a simple http server thread working. I can connect the server successful using IE6 and following url: http://127.0.0.1:5050 But when I attempt a second connect the windows symbol in the upper right corner of ie starts in motion and nothing happens it just sits there waiting for a response. The code also behaves very strangely when I try to debug it, it will jump out of the serverThread function in the middle of the stream.read loop and not return any exceptions, I'm really lost on this one. The code also really seems to stumble when I use IE's refresh button rather than typing in the URL if you can believe it.
I have included the class in question below stripped to the bone. Any feedback would be appreciated. [...]
That's a singlethreaded implementation -- the main server thread should spawn a new thread for each request accepted. Check out the Cassini web server at www.asp.net.
Cheers, -- Joerg Jooss jo*********@gmx .net
News" <nospam> wrote: Thanks Joerg,
Cassini looks like it will be very helpful, it is definitely a more complete package than any of the examples I have come across to date, but I'd still like to understand why my simple example doesn't work as expected before getting into more complex examples. Even though it is single threaded shouldn't the listener make itself available again once it has finished processing a request? I'd also like to try to understand why it is not consistently serving up the first request.
Well, it should. After looking at your code again, there are still a
couple of issues that need to be taken care of:
1. Utter lack of exception handling ;-) This is quite dangerous anyway,
but since 99.9% of all exceptions are to be expected in the main server
thread, a simple try/catch in main() won't help.
2. Review the docs for TcpClient and NetworkStream on MSDN. For example:
"You must close the NetworkStream when you are through sending and
receiving data. Closing TcpClient does not release the NetworkStream."
Unfortunately, MSDN's own samples are sometimes wrong if this is true. I
guess not adhering to those guidelines may have weird side effects.
3. If you know Java (or better its java.net package), a multithreaded
HTTP server can be found at http://www.devhood.com/tutorials/tut...utorial_id=396
&printer=t
ServerSocket becomes TcpListener, and accept() becomes either
AcceptSocket() or AcceptTcpClient () etc.
Cheers,
--
Joerg Jooss jo*********@gmx .net
Thanks for the tips. Believe it or not removing the read loop and replacing
it with a single read command helped correct the problem. I still haven't
figured out why but I'll keep playing with it until it hits me.
Once the first request was working closing the socket, as you suggested,
made a huge difference in performance. I'm surprised it was not in any of
the online examples I looked at.
As far as exception handling goes - I know it is less than optimal :). I
removed any code that was not necessary for the server to run, once I
determine that exceptions were not being thrown when my code was
misbehaving, in order to make pin pointing the problem a little easier, but
don't worry, I will be sure to add plenty of exception handling once I am
happy with the basic functionality.
Thanks Again,
Dave
"Joerg Jooss" <jo*********@gm x.net> wrote in message
news:eH******** *****@TK2MSFTNG P10.phx.gbl... News" <nospam> wrote:
Thanks Joerg,
Cassini looks like it will be very helpful, it is definitely a more complete package than any of the examples I have come across to date, but I'd still like to understand why my simple example doesn't work as expected before getting into more complex examples. Even though it is single threaded shouldn't the listener make itself available again once it has finished processing a request? I'd also like to try to understand why it is not consistently serving up the first request.
Well, it should. After looking at your code again, there are still a couple of issues that need to be taken care of:
1. Utter lack of exception handling ;-) This is quite dangerous anyway, but since 99.9% of all exceptions are to be expected in the main server thread, a simple try/catch in main() won't help.
2. Review the docs for TcpClient and NetworkStream on MSDN. For example: "You must close the NetworkStream when you are through sending and receiving data. Closing TcpClient does not release the NetworkStream."
Unfortunately, MSDN's own samples are sometimes wrong if this is true. I guess not adhering to those guidelines may have weird side effects.
3. If you know Java (or better its java.net package), a multithreaded HTTP server can be found at http://www.devhood.com/tutorials/tut...utorial_id=396 &printer=t
ServerSocket becomes TcpListener, and accept() becomes either AcceptSocket() or AcceptTcpClient () etc.
Cheers, -- Joerg Jooss jo*********@gmx .net
Dave,
There's a couple problems. First your reading until you get a zero
byte return. That will only happen when the socket is closed by the
client. The client won't close the socket because it's waiting for
your response.
You need to read until you get to the end of the HTTP request. So
read and append to a buffer. Then check the buffer end for
'\r\n\r\n'.
Second is IE is using HTTP 1.1 with keep alives. So it's going to
keep reading until either you close the socket or send the correct
HTTP 1.1 response. Frankly I'm not sure what that is - been a while
since I read the HTTP spec.
Easy thing to do is simply close the socket. Which is not happening
with your code because you've got an un-disposed network stream
that's holding the socket open.
Here's your ServiceThread function modified to do what I think your
after:
private void ServerThread()
{
int requestCounter = 0;
Byte[] buffer = new Byte[1024];
char[] charBuf = new char[1024];
StringBuilder sb = new StringBuilder(1 024,4096);
while(true)
{
using( TcpClient client = _listener.Accep tTcpClient())
{
using( NetworkStream stream = client.GetStrea m())
{
++requestCounte r;
int bytesRead;
int charsConverted;
while((bytesRea d = stream.Read(buf fer, 0, buffer.Length)) != 0)
{
charsConverted =
Encoding.ASCII. GetChars(buffer ,0,bytesRead,ch arBuf,0);
if(charsConvert ed > 0)
{
sb.Append(charB uf,0,charsConve rted);
int currentRequestS ize = sb.Length;
if(currentReque stSize > 3)
{
if('\n' == sb[currentRequestS ize-1] && '\r' ==
sb[currentRequestS ize-2] &&
'\n' == sb[currentRequestS ize-3] && '\r' ==
sb[currentRequestS ize-4])
{
// we've got our request
break;
}
}
// else we don't have a full HTTP request yet so keep reading
}
else
{
// if we don't throw here we risk missing the \r\n and hanging
for more input
throw new ApplicationExce ption("failed to convert HTTP request
to ascii characters");
}
}
string request = "request [" + requestCounter. ToString() + "] " +
sb.ToString();
sb.Remove(0,sb. Length);
string output = "HTTP/1.1 200 OK\r\n";
output = output + "Content-type: text/plain\r\n";
output = output + "Content-length: " + request.Length + "\r\n";
output = output + "\r\n";
output = output + request;
byte[] msg = System.Text.Enc oding.ASCII.Get Bytes(output);
stream.Write(ms g, 0, msg.Length);
} // using stream
} // using client
} // forever
} // end ServerThread Davewrote:
Thanks for the tips. Believe it or not removing the read loop and
replacing it with a single read command helped correct the problem. I still
haven't figured out why but I'll keep playing with it until it hits me.
Once the first request was working closing the socket, as you
suggested, made a huge difference in performance. I'm surprised it was not in
any of the online examples I looked at.
As far as exception handling goes - I know it is less than optimal
:). I removed any code that was not necessary for the server to run, once
I determine that exceptions were not being thrown when my code was misbehaving, in order to make pin pointing the problem a little
easier, but don't worry, I will be sure to add plenty of exception handling once
I am happy with the basic functionality.
Thanks Again, Dave
"Joerg Jooss" <jo*********@gm x.net> wrote in message news:eH******** *****@TK2MSFTNG P10.phx.gbl... News" <nospam> wrote:
Thanks Joerg,
Cassini looks like it will be very helpful, it is definitely a more complete package than any of the examples I have come across to date, but I'd still like to understand why my simple example
doesn't work as expected before getting into more complex examples. Even though it is single threaded shouldn't the listener make itself available again once it has finished processing a request? I'd
also like to try to understand why it is not consistently serving up the first request.
Well, it should. After looking at your code again, there are still
a couple of issues that need to be taken care of:
1. Utter lack of exception handling ;-) This is quite dangerous
anyway, but since 99.9% of all exceptions are to be expected in the main
server thread, a simple try/catch in main() won't help.
2. Review the docs for TcpClient and NetworkStream on MSDN. For
example: "You must close the NetworkStream when you are through sending and receiving data. Closing TcpClient does not release the
NetworkStream." Unfortunately, MSDN's own samples are sometimes wrong if this is
true. I guess not adhering to those guidelines may have weird side effects.
3. If you know Java (or better its java.net package), a
multithreaded HTTP server can be found at http://www.devhood.com/tutorials/tut...utorial_id=396 &printer=t
ServerSocket becomes TcpListener, and accept() becomes either AcceptSocket() or AcceptTcpClient () etc.
Cheers, -- Joerg Jooss jo*********@gmx .net[/quote]
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Thanks for the help Mike. I've found that closing the socket helped quit a
bit, obvious I should spend a little time with the http 1.1 spec. Your
explanation of the read issue also makes things a little clearer. My
solution to this point was to open a second stream for writing after the
read stream closed, which is obviously not the most efficient way to handle
this situation. I appreciate you taking the time to include a code example
as well, it has been most helpful.
Thanks Again,
Dave
"Mike Junkin" <mi********@hot mail-dot-com.no-spam.invalid> wrote in message
news:3f******** **@127.0.0.1... Dave,
There's a couple problems. First your reading until you get a zero byte return. That will only happen when the socket is closed by the client. The client won't close the socket because it's waiting for your response.
You need to read until you get to the end of the HTTP request. So read and append to a buffer. Then check the buffer end for '\r\n\r\n'.
Second is IE is using HTTP 1.1 with keep alives. So it's going to keep reading until either you close the socket or send the correct HTTP 1.1 response. Frankly I'm not sure what that is - been a while since I read the HTTP spec.
Easy thing to do is simply close the socket. Which is not happening with your code because you've got an un-disposed network stream that's holding the socket open.
Here's your ServiceThread function modified to do what I think your after:
private void ServerThread() { int requestCounter = 0;
Byte[] buffer = new Byte[1024]; char[] charBuf = new char[1024]; StringBuilder sb = new StringBuilder(1 024,4096);
while(true) { using( TcpClient client = _listener.Accep tTcpClient()) { using( NetworkStream stream = client.GetStrea m()) { ++requestCounte r;
int bytesRead; int charsConverted;
while((bytesRea d = stream.Read(buf fer, 0, buffer.Length)) != 0) { charsConverted = Encoding.ASCII. GetChars(buffer ,0,bytesRead,ch arBuf,0);
if(charsConvert ed > 0) { sb.Append(charB uf,0,charsConve rted);
int currentRequestS ize = sb.Length;
if(currentReque stSize > 3) { if('\n' == sb[currentRequestS ize-1] && '\r' == sb[currentRequestS ize-2] && '\n' == sb[currentRequestS ize-3] && '\r' == sb[currentRequestS ize-4]) { // we've got our request break; } } // else we don't have a full HTTP request yet so keep reading } else { // if we don't throw here we risk missing the \r\n and hanging for more input
throw new ApplicationExce ption("failed to convert HTTP request to ascii characters"); } }
string request = "request [" + requestCounter. ToString() + "] " + sb.ToString();
sb.Remove(0,sb. Length);
string output = "HTTP/1.1 200 OK\r\n"; output = output + "Content-type: text/plain\r\n"; output = output + "Content-length: " + request.Length + "\r\n"; output = output + "\r\n"; output = output + request;
byte[] msg = System.Text.Enc oding.ASCII.Get Bytes(output);
stream.Write(ms g, 0, msg.Length);
} // using stream } // using client } // forever } // end ServerThread
Davewrote: Thanks for the tips. Believe it or not removing the read loop and replacing it with a single read command helped correct the problem. I still haven't figured out why but I'll keep playing with it until it hits me.
Once the first request was working closing the socket, as you suggested, made a huge difference in performance. I'm surprised it was not in any of the online examples I looked at.
As far as exception handling goes - I know it is less than optimal :). I removed any code that was not necessary for the server to run, once I determine that exceptions were not being thrown when my code was misbehaving, in order to make pin pointing the problem a little easier, but don't worry, I will be sure to add plenty of exception handling once I am happy with the basic functionality.
Thanks Again, Dave
"Joerg Jooss" <jo*********@gm x.net> wrote in message news:eH******** *****@TK2MSFTNG P10.phx.gbl... News" <nospam> wrote:
Thanks Joerg,
Cassini looks like it will be very helpful, it is definitely a more complete package than any of the examples I have come across to date, but I'd still like to understand why my simple example doesn't work as expected before getting into more complex examples. Even though it is single threaded shouldn't the listener make itself available again once it has finished processing a request? I'd also like to try to understand why it is not consistently serving up the first request.
Well, it should. After looking at your code again, there are still a couple of issues that need to be taken care of:
1. Utter lack of exception handling ;-) This is quite dangerous anyway, but since 99.9% of all exceptions are to be expected in the main server thread, a simple try/catch in main() won't help.
2. Review the docs for TcpClient and NetworkStream on MSDN. For example: "You must close the NetworkStream when you are through sending and receiving data. Closing TcpClient does not release the NetworkStream." Unfortunately, MSDN's own samples are sometimes wrong if this is
true. I guess not adhering to those guidelines may have weird side effects.
3. If you know Java (or better its java.net package), a multithreaded HTTP server can be found at http://www.devhood.com/tutorials/tut...utorial_id=396 &printer=t
ServerSocket becomes TcpListener, and accept() becomes either AcceptSocket() or AcceptTcpClient () etc.
Cheers, -- Joerg Jooss jo*********@gmx .net[/quote] ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet
News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000
Newsgroups ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption
=--- This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Jeffery J. Morgan |
last post by:
Hello,
I have a problem that I have not been able to resolve. I have a feeling that
it is related to a security policy, but not sure which one.
Within our domain, there are developers that are working on their local IIS
servers on .ASP projects. We have some Macintosh computers that we are
trying to test from, but they are not able to access the IIS servers.
Currently using forms authentication in the project. I did some testing and...
|
by: Charles Law |
last post by:
I have a user control created on the main thread. Let's say, for arguments
sake, that it has a single property that maintains a private variable. If I
want to set that property from a worker thread, do I need to use
UserControl1.Invoke to set it, or can I just set it? After all, it is only
changing a private variable.
TIA
Charles
|
by: Chris |
last post by:
Hi,
I need some help here.
Is it possible to close an HTTP connection in the middle of a php
script?
For example:
<html>
|
by: Richard Steele (Basemap) |
last post by:
I need to be able to upload an unattended xml file from
a client's PC to our webserver on a regular basis
Can you offer any advice on the best way to do this?
The webserver would obviously have to have a port opened
to achieve this, is there any security issues regarding this?
Thank you for your help
Richard
|
by: Rein Petersen |
last post by:
Hi All,
I've recently been intrigued with this notion of "Service Streaming":
http://ajaxpatterns.org/HTTP_Streaming
in which you make use of the webserver and browsers ability to maintain
a connection using a loop on the web server. I know those of you
familiar with how IIS/asp.net (aspnet_isapi.dll) handles
HttpApplication threads (a pool) are probably very offended by this
| |
by: Zach Burnett |
last post by:
I have created a page that should unlock our local users throughout our
network. The page is simple enough. It just takes users input for the IP
Address and the User Name of the lockout computer. When they click the
unlock button A series of If Else statements decides by the I.P. Address
which site they are at. From this it calls an appropriate .bat file passing
the IP and UserName. The series of .bat files and .vbe files are located...
|
by: yannis.corre |
last post by:
Hello,
I don't understand the difference of behavior of these two
webservers :
I'm uploading a file and I launch a thread that makes some treatments
with the Request.Files.
I saw that a new .post file was created on a "upload" directory of the
ASP.Net temporary files.
With the internal webserver :
|
by: RvGrah |
last post by:
I'm completely new to using background threading, though I have
downloaded and run through several samples and understood how they
worked.
My question is:
I have an app whose primary form will almost always lead to the user
opening a certain child window that's fairly resource intensive to
load. Is it possible to load this form in a backgroundworker and then
use the Show method and hide method as necessary? Anyone know of
|
by: vstud |
last post by:
Hello,
I need some begginers help here with the following:
I developed ASP 2.0 application on my personal machine which is using the
wwwroot localhost and everything works fine.
my question is how do I move/transform my asp application to work on our webserver (how do i deploy it ). ?
to be more specific, in my asp application (using the ms visual studio 2005 ide)
the query points to my local Access d.b. that reside on local pc hard...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |