Attachment 'webserver.py'

Download

   1 #!/usr/bin/env python
   2 import socket
   3 import sys
   4 import os
   5 import signal
   6 import re
   7 
   8 
   9 
  10 # Vytvorime TCP socket
  11 s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  12 # Po ukonceni zostane niekedy socket v stave FIN_WAIT_2
  13 # REUSEADDR umozni opatovny bind.
  14 s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
  15 # Naviazeme ho na port 2222 pre vsetky lokalne adresy
  16 s.bind(('',2222))
  17 # Najviac 5 spojeni bude cakat vo fronte
  18 s.listen(5)
  19 
  20 # Toto je kvoli tomu, aby nam nezostavali zombie 
  21 # procesy a neprerusoval nas signal SIGCHLD
  22 signal.signal(signal.SIGCHLD,signal.SIG_IGN)
  23 
  24 try:
  25     while True:
  26         connected_socket,address=s.accept()
  27         print 'Connected by',address
  28         # Po pripojeni klienta sa forkneme.
  29         # Child proces obsluzi klienta a zavola sys.exit()
  30         # Parent proces ocakava
  31         # dalsieho klienta.
  32         pid_chld=os.fork()
  33         if pid_chld<0:
  34             print "fork vratil chybu"
  35             sys.exit(1)
  36         if pid_chld==0:
  37             # Toto robi child proces.
  38             # Vytvorime si file object z pripojeneho
  39             # socketu
  40             f=connected_socket.makefile()
  41             line=f.readline()
  42             m=re.match('^GET *([^ ]*).*$',line)
  43             response='Client said:\n'+line
  44             for line in f:
  45                 response+=line
  46                 # CR LF ukoncuje request
  47                 if line=='\r\n':
  48                     break
  49             f.write('HTTP/1.1 200 OK')
  50             f.write('Content-type: text/plain\r\n')
  51             f.write('Content-length: %d\r\n' % len(response))
  52             f.write('\r\n')
  53             f.write(response)
  54             # f je duplikovany connected_socket, preto
  55             # ho musime zavriet osobitne.
  56             f.close()
  57             # Takymto sposobom sa spravne zatvara
  58             # socket, v prikladoch v dokumentacii to
  59             # je zle.
  60             connected_socket.shutdown(socket.SHUT_RDWR)
  61             connected_socket.close()
  62             print address,'disconnected'
  63             sys.exit(0)
  64 except KeyboardInterrupt:
  65     pass
  66 s.close()

Attached Files

To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.

You are not allowed to attach a file to this page.