Yurttas/PL/SL/python/docs/core-python-programming/doc/16/lib/Socket Example.html

From ZCubes Wiki
Revision as of 19:19, 7 November 2013 by MassBot1 (talk | contribs) (Created page with "<div class="navigation"> {| width="100%" cellspacing="2" align="center" | yurttas/PL/SL/python/docs/core-python-programming/doc/16/lib/module-select.html|[[Image:yurtta...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

7.2.2 Example

Here are two minimal example programs using the TCP/IP protocol: a server that echoes all data that it receives back (servicing only one client), and a client using it. Note that a server must perform the sequence socket(), bind(), listen(), accept() (possibly repeating the accept() to service more than one client), while a client only needs the sequence socket(), connect(). Also note that the server does not send()/recv() on the socket it is listening on but on the new socket returned by accept().

# Echo server program from socket import * HOST = '' # Symbolic name meaning the local host PORT = 50007 # Arbitrary non-privileged server s = socket(AF_INET, SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close()
# Echo client program from socket import * HOST = 'daring.cwi.nl' # The remote host PORT = 50007 # The same port as used by the server s = socket(AF_INET, SOCK_STREAM) s.connect((HOST, PORT)) s.send('Hello, world') data = s.recv(1024) s.close() print 'Received', `data`

See Also:

Module SocketServer:
classes that simplify writing network servers.