Klient a server (TCP)

   1 #!/usr/bin/env python
   2 import socket
   3 import sys
   4 
   5 # Skuste: 
   6 # telnet 127.0.0.1 2222
   7 # ukoncite CTRL-] a potom quit
   8 
   9 # Vytvorime TCP socket
  10 s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  11 # Naviazeme ho na port 2222 pre vsetky lokalne adresy
  12 s.bind(('',2222))
  13 # Najviac 5 spojeni bude cakat vo fronte
  14 s.listen(5)
  15 try:
  16     while True:
  17         connected_socket,address=s.accept()
  18         print 'Connected by %s' % address
  19         while True:
  20             data=connected_socket.recv(1024)
  21             if not data:
  22                 break
  23             sys.stdout.write(data)
  24         connected_socket.close()
  25 except KeyboardInterrupt:
  26     pass
  27 s.close()
miniserver.py

   1 #!/usr/bin/env python
   2 import socket
   3 import sys
   4 import os
   5 import signal
   6 
   7 
   8 # Skuste: 
   9 # telnet 127.0.0.1 2222
  10 # ukoncite CTRL-] a potom quit
  11 
  12 # Vytvorime TCP socket
  13 s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  14 # Naviazeme ho na port 2222 pre vsetky lokalne adresy
  15 s.bind(('',2222))
  16 # Najviac 5 spojeni bude cakat vo fronte
  17 s.listen(5)
  18 
  19 # Toto je kvoli tomu, aby nezostavali zombie 
  20 # procesy
  21 signal.signal(signal.SIGCHLD,signal.SIG_IGN)
  22 
  23 try:
  24     while True:
  25         connected_socket,address=s.accept()
  26         print 'Connected by',address
  27         pid_chld=os.fork()
  28         if pid_chld<0:
  29             print "fork vratil chybu"
  30             sys.exit(1)
  31         if pid_chld==0:
  32             while True:
  33                 data=connected_socket.recv(1024)
  34                 if not data:
  35                     break
  36             connected_socket.close()
  37             print address,'disconnected'
  38             sys.exit(0)
  39 except KeyboardInterrupt:
  40     pass
  41 s.close()
miniserver_fork.py

PocitacoveSiete/TCPSocket (last edited 2008-11-21 12:15:01 by GejzaJenca)