Sockets are the lead pipes of computer networks: they let you connect with other devices so that information can flow freely. As you might expect, they're widely used on the Internet. Peyton McCullough explains how to code sockets in Python.
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:
That wasn't so hard, was it? Of course not. As I said, sockets are extremely easy to learn and use in your scripts.
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: