Problem with socket

Justin Sheehy justin at iago.org
Wed Feb 13 18:00:06 CET 2002


"DelPiccolo Ivano" <ivano.delpiccolo at degroof.be> writes:

> I tried to impement a very simple client-server application.
> Hre's the output from the server part :
>
> Traceback (most recent call last):
>   File "C:\Python22\Pythonwin\pywin\framework\scriptutils.py", line 301, in
> RunScript
>     exec codeObject in __main__.__dict__
>   File "D:\server.py", line 10, in ?
>     data = conn.recv(1024)
>   File "<string>", line 1, in recv
>   File "C:\Python22\lib\socket.py", line 159, in __getattr__
>     raise error(9, 'Bad file descriptor')
> error: (9, 'Bad file descriptor')
>
>
> Here's my server.py :
> import socket
> host = ''
> port = 50007
> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> s.bind ((host,port))
> s.listen(1)
> conn,addr=s.accept()
> print 'Connected by : ', addr
> while 1:
>     data = conn.recv(10)
>     if not data : break
>     conn.send(data)
>     conn.close()

The contents of the while loop is almost certainly not what you want.

The first recv will generally return some data.  You then proceed to
send data back, and then _close the socket_. After that, the while
loop starts over and you try to read again... from the socket you just
closed.

If you just change the loop from:

while 1: 
    data = conn.recv(10) 
    if not data : break 
    conn.send(data) 
    conn.close() 

to this:

while 1:    
    data = conn.recv(10)
    if not data : break
    conn.send(data)
conn.close()

you should be all set with regard to this example.

-Justin

 





More information about the Python-list mailing list