home *** CD-ROM | disk | FTP | other *** search
/ The Datafile PD-CD 5 / DATAFILE_PDCD5.iso / utilities / p / python / pyhtmldoc / s / socket_exa < prev    next >
Encoding:
Text File  |  1996-11-14  |  1.6 KB  |  42 lines

  1. <TITLE>Socket Example -- Python library reference</TITLE>
  2. Prev: <A HREF="../s/socket_objects" TYPE="Prev">Socket Objects</A>  
  3. Up: <A HREF="../s/socket" TYPE="Up">socket</A>  
  4. Top: <A HREF="../t/top" TYPE="Top">Top</A>  
  5. <H2>7.2.2. Example</H2>
  6. Here are two minimal example programs using the TCP/IP protocol: a
  7. server that echoes all data that it receives back (servicing only one
  8. client), and a client using it.  Note that a server must perform the
  9. sequence <CODE>socket</CODE>, <CODE>bind</CODE>, <CODE>listen</CODE>, <CODE>accept</CODE>
  10. (possibly repeating the <CODE>accept</CODE> to service more than one client),
  11. while a client only needs the sequence <CODE>socket</CODE>, <CODE>connect</CODE>.
  12. Also note that the server does not <CODE>send</CODE>/<CODE>receive</CODE> on the
  13. socket it is listening on but on the new socket returned by
  14. <CODE>accept</CODE>.
  15. <P>
  16. <UL COMPACT><CODE># Echo server program<P>
  17. from socket import *<P>
  18. HOST = ''                 # Symbolic name meaning the local host<P>
  19. PORT = 50007              # Arbitrary non-privileged server<P>
  20. s = socket(AF_INET, SOCK_STREAM)<P>
  21. s.bind(HOST, PORT)<P>
  22. s.listen(1)<P>
  23. conn, addr = s.accept()<P>
  24. print 'Connected by', addr<P>
  25. while 1:<P>
  26.     data = conn.recv(1024)<P>
  27.     if not data: break<P>
  28.     conn.send(data)<P>
  29. conn.close()<P>
  30. </CODE></UL>
  31. <UL COMPACT><CODE># Echo client program<P>
  32. from socket import *<P>
  33. HOST = 'daring.cwi.nl'    # The remote host<P>
  34. PORT = 50007              # The same port as used by the server<P>
  35. s = socket(AF_INET, SOCK_STREAM)<P>
  36. s.connect(HOST, PORT)<P>
  37. s.send('Hello, world')<P>
  38. data = s.recv(1024)<P>
  39. s.close()<P>
  40. print 'Received', `data`<P>
  41. </CODE></UL>
  42.