Python Socket problem
Fredrik Lundh
effbot at telia.com
Tue Oct 24 10:54:05 EDT 2000
Sam Schulenburg wrote:
> I am trying to use sockets ( I really do not know what I am doing) and
> have obtained the following results:
>
> from socket import *
> Sock = socket(AF_INET,SOCK_STREAM)
> MySocket = Sock.connect(('192.168.100.101',80))
> MySocket.send('DoTheTest \n\r\0')
> MySocket.close()
>
> The above will send the DOTheTest mesage to 192.168.100.101 and the the
> DoTheTest will execute on the server. What I need to do next is obtain
> the responce from the test.
you're close. but connect doesn't return a new socket;
it connects the existing socket to a remote server:
from socket import *
Sock = socket(AF_INET,SOCK_STREAM)
Sock.connect(('localhost',80))
Sock.send('DoTheTest \n\r\0')
Sock.close()
(and yes, "execute DoTheTest" sounds a bit dangerous, but I
assume you know what you're doing...)
client sockets can only be used once. to make another
request from the same program, create a new socket.
> I tried the following code:
>
> Sock = socket(AF_INET,SOCK_STREAM)
> MySocket = Sock.connect(('192.168.100.101',80))
> Data = MySocket.recv()
> MySocket.close()
> print Data
clients connect, servers bind, listen and accept:
from socket import *
# create a listening socket
Sock = socket(AF_INET,SOCK_STREAM)
# bind it to a port
Sock.bind(("", 80))
# create a small listening queue
Sock.listen(1)
while 1:
# wait for a client to connect
NewSock, Info = Sock.accept()
print "incoming connection from", Info
# read a package from the client
print NewSock.recv(1024)
NewSock.close()
break # shutdown
(note that the listening socket can be reused; just
remove the "break" to have the loop process another
command)
for more examples (and better ways to do this), see the
"network" chapter in the eff-bot guide.
</F>
<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->
More information about the Python-list
mailing list