account of your own like the one I’m using on learning-python.com, simply run client
and server examples on the same machine, localhost, as shown earlier; all you need
then is a computer that allows sockets, and most do.
Second, the socket module generally raises exceptions if you ask for something invalid.
For instance, trying to connect to a nonexistent server (or unreachable servers, if you
have no Internet link) fails:
C:\...\PP4E\Internet\Sockets> python echo-client.py http://www.nonesuch.com hello
Traceback (most recent call last):
File "echo-client.py", line 24, in <module>
sockobj.connect((serverHost, serverPort)) # connect to server machine...
socket.error: [Errno 10060] A connection attempt failed because the connected
party did not properly respond after a period of time, or established connection
failed because connected host has failed to respond
Finally, also be sure to kill the server process before restarting it again, or else the port
number will still be in use, and you’ll get another exception; on my remote server
machine:
[...]$ ps -x
PID TTY STAT TIME COMMAND
5378 pts/0 S 0:00 python echo-server.py
22017 pts/0 Ss 0:00 -bash
26805 pts/0 R+ 0:00 ps –x
[...]$ python echo-server.py
Traceback (most recent call last):
File "echo-server.py", line 14, in <module>
sockobj.bind((myHost, myPort)) # bind it to server port number
socket.error: [Errno 10048] Only one usage of each socket address (protocol/
network address/port) is normally permitted
A series of Ctrl-Cs will kill the server on Linux (be sure to type fg to bring it to the
foreground first if started with an &):
[...]$ fg
python echo-server.py
Traceback (most recent call last):
File "echo-server.py", line 18, in <module>
connection, address = sockobj.accept() # wait for next client connect
KeyboardInterrupt
As mentioned earlier, a Ctrl-C kill key combination won’t kill the server on my Win-
dows 7 machine, however. To kill the perpetually running server process running lo-
cally on Windows, you may need to start Task Manager (e.g., using a Ctrl-Alt-Delete
key combination), and then end the Python task by selecting it in the process listbox
that appears. Closing the window in which the server is running will also suffice on
Windows, but you’ll lose that window’s command history. You can also usually kill a
server on Linux with a kill −9 pid shell command if it is running in another window
or in the background, but Ctrl-C requires less typing.
Socket Programming | 797