home *** CD-ROM | disk | FTP | other *** search
- <TITLE>Socket Example -- Python library reference</TITLE>
- Prev: <A HREF="../s/socket_objects" TYPE="Prev">Socket Objects</A>
- Up: <A HREF="../s/socket" TYPE="Up">socket</A>
- Top: <A HREF="../t/top" TYPE="Top">Top</A>
- <H2>7.2.2. Example</H2>
- 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 <CODE>socket</CODE>, <CODE>bind</CODE>, <CODE>listen</CODE>, <CODE>accept</CODE>
- (possibly repeating the <CODE>accept</CODE> to service more than one client),
- while a client only needs the sequence <CODE>socket</CODE>, <CODE>connect</CODE>.
- Also note that the server does not <CODE>send</CODE>/<CODE>receive</CODE> on the
- socket it is listening on but on the new socket returned by
- <CODE>accept</CODE>.
- <P>
- <UL COMPACT><CODE># Echo server program<P>
- from socket import *<P>
- HOST = '' # Symbolic name meaning the local host<P>
- PORT = 50007 # Arbitrary non-privileged server<P>
- s = socket(AF_INET, SOCK_STREAM)<P>
- s.bind(HOST, PORT)<P>
- s.listen(1)<P>
- conn, addr = s.accept()<P>
- print 'Connected by', addr<P>
- while 1:<P>
- data = conn.recv(1024)<P>
- if not data: break<P>
- conn.send(data)<P>
- conn.close()<P>
- </CODE></UL>
- <UL COMPACT><CODE># Echo client program<P>
- from socket import *<P>
- HOST = 'daring.cwi.nl' # The remote host<P>
- PORT = 50007 # The same port as used by the server<P>
- s = socket(AF_INET, SOCK_STREAM)<P>
- s.connect(HOST, PORT)<P>
- s.send('Hello, world')<P>
- data = s.recv(1024)<P>
- s.close()<P>
- print 'Received', `data`<P>
- </CODE></UL>
-