473,791 Members | 3,105 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Select weirdness

Here's my code. It's a teeny weeny little HTTP server. (I'm not really
trying to reinvent the wheel here. What I'm really doing is writing a
dispatching proxy server, but this is the shortest way to illustrate the
problem I'm having):

from SocketServer import *
from socket import *
from select import select

class myHandler(Strea mRequestHandler ):
def handle(self):
print '>>>>>>>>>>>'
while 1:
sl = select([self.rfile],[],[])[0]
if sl:
l = self.rfile.read line()
if len(l)<3: break
print l,
pass
pass
print>>self.wfi le, 'HTTP/1.0 200 OK'
print>>self.wfi le, 'Content-type: text/plain'
print>>self.wfi le
print>>self.wfi le, 'foo'
self.rfile.clos e()
self.wfile.clos e()
print '<<<<<<<<<<<<'
pass
pass

def main():
server = TCPServer(('',8 080), myHandler)
server.serve_fo rever()
pass

if __name__ == '__main__': main()
If I telnet into this server and type in an HTTP request manually it
works fine. But when I try to access this with a browser (I've tried
Firefox and Safari -- both do the same thing) it hangs immediately after
reading the first line in the request (i.e. before reading the first
header).

When I click the "stop" button in the browser it breaks the logjam and
the server reads the headers (but then of course it dies trying to write
the response to a now-closed socket).

The only difference I can discern is that the browser send \r\n for
end-of-line while telnet just sends \n. But I don't see why that should
make any difference. So I'm stumped. Any clues would be much
appreciated.

Thanks,
rg
Apr 22 '07 #1
18 1510
Ron Garret wrote:
print>>self.wfi le, 'HTTP/1.0 200 OK'
print>>self.wfi le, 'Content-type: text/plain'
print>>self.wfi le
print>>self.wfi le, 'foo'
[...]
If I telnet into this server and type in an HTTP request manually
it works fine. But when I try to access this with a browser (I've
tried Firefox and Safari -- both do the same thing) it hangs
immediately after reading the first line in the request (i.e.
before reading the first header).
Could the problem be that print ends lines with "\r\n" not on all
platforms? Try doing it explicitly.
The only difference I can discern is that the browser send \r\n
for end-of-line while telnet just sends \n.
Then, I think, your telnet client is broken. I've seem multiple
applications relying on telnet or similar protocols which
required "\r\n" as end-of-line. E. g. I needed to hack
twisted.protoco ls.basic.LineRe ceiverFactory since it showed the
exact behaviour you described for browsers. It showed up because
busybox' telnet only sends \n as EOL.
But I don't see why that should make any difference.
Easy. If you only accept "\r\n" as EOL, you'll wait forever unless
you really receive it.

Regards,
Björn

--
BOFH excuse #81:

Please excuse me, I have to circuit an AC line through my head to
get this database working.

Apr 22 '07 #2
Ron Garret wrote:
Here's my code. It's a teeny weeny little HTTP server. (I'm not really
trying to reinvent the wheel here. What I'm really doing is writing a
dispatching proxy server, but this is the shortest way to illustrate the
problem I'm having):

from SocketServer import *
from socket import *
from select import select

class myHandler(Strea mRequestHandler ):
def handle(self):
print '>>>>>>>>>>>'
while 1:
sl = select([self.rfile],[],[])[0]
if sl:
l = self.rfile.read line()
if len(l)<3: break
print l,
pass
pass
print>>self.wfi le, 'HTTP/1.0 200 OK'
print>>self.wfi le, 'Content-type: text/plain'
print>>self.wfi le
print>>self.wfi le, 'foo'
self.rfile.clos e()
self.wfile.clos e()
print '<<<<<<<<<<<<'
pass
pass

You shouldn't use a select() of your own inside the handle method.
The socketserver takes care of that for you.

What you need to do is read the input from the socket until you've reached
the end-of-input marker. That marker is an empty line containing just "\r\n"
when dealing with HTTP GET requests.

Any reason don't want to use the BasicHTTPServer that comes with Python?

Anyway, try the following instead:

from SocketServer import *
from socket import *
from select import select

class myHandler(Strea mRequestHandler ):
def handle(self):
print '>>>>>>>>>>>'
while True:
l = self.rfile.read line()
print repr(l)
if not l or l=='\r\n':
break
print>>self.wfi le, 'HTTP/1.0 200 OK'
print>>self.wfi le, 'Content-type: text/plain'
print>>self.wfi le
print>>self.wfi le, 'foo'
self.rfile.clos e()
self.wfile.clos e()
print '<<<<<<<<<<<<'

def main():
server = TCPServer(('',8 080), myHandler)
server.serve_fo rever()

if __name__ == '__main__': main()

--Irmen
Apr 22 '07 #3
In article <46************ *********@news. xs4all.nl>,
Irmen de Jong <ir**********@x s4all.nlwrote:
Ron Garret wrote:
Here's my code. It's a teeny weeny little HTTP server. (I'm not really
trying to reinvent the wheel here. What I'm really doing is writing a
dispatching proxy server, but this is the shortest way to illustrate the
problem I'm having):

from SocketServer import *
from socket import *
from select import select

class myHandler(Strea mRequestHandler ):
def handle(self):
print '>>>>>>>>>>>'
while 1:
sl = select([self.rfile],[],[])[0]
if sl:
l = self.rfile.read line()
if len(l)<3: break
print l,
pass
pass
print>>self.wfi le, 'HTTP/1.0 200 OK'
print>>self.wfi le, 'Content-type: text/plain'
print>>self.wfi le
print>>self.wfi le, 'foo'
self.rfile.clos e()
self.wfile.clos e()
print '<<<<<<<<<<<<'
pass
pass


You shouldn't use a select() of your own inside the handle method.
The socketserver takes care of that for you.
I don't understand why socketserver calling select should matter. (And
BTW, there are no calls to select in SocketServer.py . I'm using
Python2.5.)
What you need to do is read the input from the socket until you've reached
the end-of-input marker. That marker is an empty line containing just "\r\n"
when dealing with HTTP GET requests.

Any reason don't want to use the BasicHTTPServer that comes with Python?
Yes, but it's a long story. What I'm really doing is writing a
dispatching proxy. It reads the HTTP request and then redirects it to a
number of different servers depending on the URL. The servers are all
local and served off of unix sockets, not TCP sockets (which is why I
can't just configure Apache to do this).

The reason I'm running this weird configuration (in case you're
wondering) is because this is a development machine and multiple copies
of the same website run on it simultaneously. Each copy of the site
runs a customized server to handle AJAX requests efficiently.
>
Anyway, try the following instead:
That won't work for POST requests.

rg
Apr 22 '07 #4
In article <59************ *@mid.individua l.net>,
Bjoern Schliessmann <us************ **************@ spamgourmet.com >
wrote:
The only difference I can discern is that the browser send \r\n
for end-of-line while telnet just sends \n.
....
But I don't see why that should make any difference.

Easy. If you only accept "\r\n" as EOL, you'll wait forever unless
you really receive it.
But it's SELECT that is hanging. Select knows (or ought to know)
nothing of end-of-line markers. Readline (when it is called) is doing
the Right Thing, and my end-of-request test is (currently) reading a
line less than 3 characters long. All that is working. The problem is
that select is saying there is no input (and therefore hanging) when in
fact there is input.

rg
Apr 22 '07 #5
In article <rN************ *************** **@news.gha.cha rtermi.net>,
Ron Garret <rN*******@flow net.comwrote:
Here's my code. It's a teeny weeny little HTTP server. (I'm not really
trying to reinvent the wheel here. What I'm really doing is writing a
dispatching proxy server, but this is the shortest way to illustrate the
problem I'm having):

from SocketServer import *
from socket import *
from select import select

class myHandler(Strea mRequestHandler ):
def handle(self):
print '>>>>>>>>>>>'
while 1:
sl = select([self.rfile],[],[])[0]
if sl:
l = self.rfile.read line()
if len(l)<3: break
print l,
pass
pass
print>>self.wfi le, 'HTTP/1.0 200 OK'
print>>self.wfi le, 'Content-type: text/plain'
print>>self.wfi le
print>>self.wfi le, 'foo'
self.rfile.clos e()
self.wfile.clos e()
print '<<<<<<<<<<<<'
pass
pass

def main():
server = TCPServer(('',8 080), myHandler)
server.serve_fo rever()
pass

if __name__ == '__main__': main()
If I telnet into this server and type in an HTTP request manually it
works fine. But when I try to access this with a browser (I've tried
Firefox and Safari -- both do the same thing) it hangs immediately after
reading the first line in the request (i.e. before reading the first
header).

When I click the "stop" button in the browser it breaks the logjam and
the server reads the headers (but then of course it dies trying to write
the response to a now-closed socket).

The only difference I can discern is that the browser send \r\n for
end-of-line while telnet just sends \n. But I don't see why that should
make any difference. So I'm stumped. Any clues would be much
appreciated.
I have reproduced the problem using Telnet, so that proves it's not an
EOL issue. The problem seems to be timing-related. If I type the
request in manually it works. If I paste it in all at once, it hangs.
It's actually even weirder than that: if I pipe the request into a
telnet client then it hangs after the request line, just with a browser
(or wget). But if I literally paste the request into a window running a
telnet client, it gets past the request line and four out of seven
headers before it hangs.

rg
Apr 22 '07 #6
I think I've figured out what's going on.

First, here's the smoking gun: I changed the code as follows:

class myHandler(Strea mRequestHandler ):
def handle(self):
print '>>>>>>>>>>>'
while 1:
sl = select([self.rfile],[],[],1)[0]
print sl
l = self.rfile.read line()
if len(l)<3: break
print l,
pass

(Rest of code is unchanged.)

In other words, I select on the rfile object and added a timeout.

Here's the result when I cut-and-paste an HTTP request:
>>>>>>>>>>>
[<socket._fileob ject object at 0x6b110>]
GET /foo/baz HTTP/1.1
[<socket._fileob ject object at 0x6b110>]
Accept: */*
[<socket._fileob ject object at 0x6b110>]
Accept-Language: en
[<socket._fileob ject object at 0x6b110>]
Accept-Encoding: gzip, deflate
[<socket._fileob ject object at 0x6b110>]
Cookie: c1=18:19:55.042 196; c2=18:19:55.042 508
[]
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en)
AppleWebKit/419 (KHTM
[]
L, like Gecko) Safari/419.3
[]
Connection: keep-alive
[]
Host: localhost:8081
[]
<<<<<<<<<<<<

As you can see, the select call shows input available for a while (five
lines) and then shows no input available despite the fact that there is
manifestly still input available.

The answer is obvious: select is looking only at the underlying socket,
and not at the rfile buffers.

So... is this a bug in select? Or a bug in my code?

rg
Apr 22 '07 #7
In article <rN************ *************** **@news.gha.cha rtermi.net>,
Ron Garret <rN*******@flow net.comwrote:
The answer is obvious: select is looking only at the underlying socket,
and not at the rfile buffers.
Here is conclusive proof that there's a bug in select:

from socket import *
from select import select
s=socket(AF_INE T, SOCK_STREAM)
s.bind(('',8080 ))
s.listen(5)
f = s.accept()[0].makefile()
# Now telnet to port 8080 and enter two lines of random text
f.readline()
select([f],[],[],1)
f.readline()

Here's the sample input:

[ron@mickey:~/devel/sockets]$ telnet localhost 8081
Trying ::1...
telnet: connect to address ::1: Connection refused
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
123
321
And this is the result:
>>f.readline( )
'123\r\n'
>>select([f],[],[],1)
# After one second...
([], [], [])
>>f.readline( )
'321\r\n'
>>>

So this is clearly a bug, but surely I'm not the first person to have
encountered this? Is there a known workaround?

rg
Apr 22 '07 #8
Ron Garret wrote:
So this is clearly a bug, but surely I'm not the first person to have
encountered this? Is there a known workaround?
It's hard to see how this demonstrates a bug in anything, since you're
telnetting to the wrong port in your example.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
Being in love for real / It ain't like a movie screen
-- India Arie
Apr 22 '07 #9
In article <1a************ *************** ***@speakeasy.n et>,
Erik Max Francis <ma*@alcyone.co mwrote:
Ron Garret wrote:
So this is clearly a bug, but surely I'm not the first person to have
encountered this? Is there a known workaround?

It's hard to see how this demonstrates a bug in anything, since you're
telnetting to the wrong port in your example.
Geez you people are picky. Since I ran this several times I ran into
the TIM_WAIT problem. Here's the actual transcript:

Python 2.5 (r25:51908, Mar 1 2007, 10:09:05)
[GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin
Type "help", "copyright" , "credits" or "license" for more information.
>>from socket import *
from select import select
s=socket(AF_I NET, SOCK_STREAM)
s.bind(('',80 80))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in bind
socket.error: (48, 'Address already in use')
>>s.bind(('',80 81))
s.listen(5)
f = s.accept()[0].makefile()
f.readline( )
'123\r\n'
>>select([f],[],[],1)
([], [], [])
>>f.readline( )
'321\r\n'
Apr 22 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
2179
by: Corne' Cornelius | last post by:
Hi, I'm experiencing some weirdness in a program, when subtracting 2 (double)'s which should result in 0, but instead it returns -1.11022e-16. It looks to me that changing the double x_step decleration to unsigned type, might help, but the compiler complains when i try that. Any ideas ? #include <iostream>
1
2437
by: (Pete Cresswell) | last post by:
TabControl on the right side of a form with two tabs: Tab #1 contains two subforms that show some dynamic query results. Tab #2 contains a ListView that gets dynamically populated as the user navigates a TreeView on the left side of the form. The first time I load the ListView, if the tab containing it is not selected (i.e. the ListView is not visible) the screen draws the ListView's contents in the upper left portion of the form -...
0
1559
by: Bruce B | last post by:
Hi group, I'm experiencing some extreme weirdness over the last week with IIS related to it's Mappings and how .NET is behaving. I can't explain the behavior as it seems very random. Our app has about 50 file extensions that we map in IIS and handle in our HTTPHandler to catch the reference and then lookup the correct content from a database. In addition, we do some magic in a HTTPModule to rewrite paths for file types we don't...
1
1288
by: VB Programmer | last post by:
My development machine has been working perfectly, writing ASP.NET apps, etc... I just went to open a project and it said: "Visual Studio .NET has detected that the specified web server is not running ASP.NET version 1.1. You will be unable to run ASP.NET Web apps or services." I reran "aspnet_regiis -i " but it still gives me the error. Here's the output:
5
2279
by: Phil Weber | last post by:
I'm attempting to debug an ASP.NET Web application in VS.NET 2003. I'm running the app and the debugger on my local machine (Windows XP Professional). I am logged in as a local administrator. In order to rule out permissions issues, I have set the processModel username to "SYSTEM" in my machine.config. Here's my problem: The ASP.NET app (compiled in debug mode) works correctly, whether I start it with debugging (F5) or without (Ctrl+F5)....
5
1708
by: David Thielen | last post by:
Hi; I am creating png files in my ASP .NET app. When I am running under Windows 2003/IIS 6, the file is not given the security permissions it should have. It does not have any permission for several users that the directory it is in has, including IUSR_JASMINE (my system is named jasmine). Here is the weird part. In my aps .net code I have the following: String jname = Request.PhysicalApplicationPath + "images\\java_" + fileNum +...
13
2373
by: Oliver Hauger | last post by:
Hello, In my html form I show a select-element and if this element is clicked I fill it per JavaScript/DOM with option-elements. I use the following code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head>
2
2374
by: JYA | last post by:
Hi. I was writing an xmltv parser using python when I faced some weirdness that I couldn't explain. What I'm doing, is read an xml file, create another dom object and copy the element from one to the other. At no time do I ever modify the original dom object, yet it gets modified.
5
4552
by: Andy Chambers | last post by:
Hi, On both Opera and Firefox, getElementsByTagName doesn't find anything apart from <optionelements inside a select element. Why is this? Here's a page that demonstrates this behaviour. I'd have thought the correct behaviour would be to show "count: 1" but instead, you get "count: 2". Is this because only <option>s <select>s?
0
9515
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,...
0
10427
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10155
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,...
0
9995
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7537
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5431
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4110
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
2
3718
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2916
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.