Sockets in Python - Connecting to the Server (Page 3 of 5 )
Let's connect to our server program. Open up the Python command line again and create a socket:
>>> import socket
>>> mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
Next, open your server program. We will now connect to the server:
>>> mySocket.connect ( ( 'localhost', 2727 ) )
This should look very familiar to the bind method, with the exception of the first argument, which tells our socket where to connect to. We now need to send our server a message:
>>> mySocket.send ( 'William Shakespeare' )
You should now see the message in the server window. Let's accept the server's reply:
>>> mySocket.recv ( 100 )
Finally, let's clean up by closing the socket:
>>> mySocket.close()
That wasn't so hard, was it? Of course not. As I said, sockets are extremely easy to learn and use in your scripts.
Datagrams
I explained datagrams a little bit in a previous section, but I will now show you how to work with datagrams. Let's take our server and rewrite it using datagrams:
import socket
mySocket = socket.socket ( socket.AF_INET, socket.SOCK_DGRAM )
mySocket.bind ( ( '', 2727 ) )
while True:
data, client = mySocket.recvfrom ( 100 )
print 'We have received a datagram from', client
print data
mySocket.sendto ( 'Green-eyed datagram.', client )
While our datagram server is very similar to our stream server, it also has obvious differences. Notice how we never use the listen method, and note how we use recvfrom and sendto rather than accept, recv and send.
Let's connect to our server through the command line:
>>> import socket
>>> mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
>>> mySocket.sendto ( 'Wherefore art thou?', ( 'localhost', 2727 ) )
>>> data, server = mySocket.recvfrom ( 100 )
>>> print data
As with the server, it is both similar to and different from the other client's code.
Next: Sockets...Simplified >>
More Python Articles
More By Peyton McCullough