Commits

Gennadiy Zlobin committed 722f2cc

Initial commit

  • Participants

Comments (0)

Files changed (11)

+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>pyserver</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+		<buildCommand>
+			<name>org.python.pydev.PyDevBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+	</buildSpec>
+	<natures>
+		<nature>org.python.pydev.pythonNature</nature>
+	</natures>
+</projectDescription>

File .pydevproject

+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<?eclipse-pydev version="1.0"?>
+
+<pydev_project>
+<pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">Default</pydev_property>
+<pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 2.6</pydev_property>
+<pydev_pathproperty name="org.python.pydev.PROJECT_SOURCE_PATH">
+<path>/pyserver/src</path>
+</pydev_pathproperty>
+</pydev_project>

File .settings/org.eclipse.core.resources.prefs

+#Sun Mar 13 18:06:26 NOVT 2011
+eclipse.preferences.version=1
+encoding//src/pyserver.py=utf-8

File src/daemon.py

+#!/usr/bin/env python
+ 
+import sys, os, time, atexit
+from signal import SIGTERM
+ 
+class Daemon:
+    """
+    A generic daemon class.
+   
+    Usage: subclass the Daemon class and override the run() method
+    """
+    def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
+        self.stdin = stdin
+        self.stdout = stdout
+        self.stderr = stderr
+        self.pidfile = pidfile
+      
+    def daemonize(self):
+        """
+        do the UNIX double-fork magic, see Stevens' "Advanced
+        Programming in the UNIX Environment" for details (ISBN 0201563177)
+        http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
+        """
+        try:
+            pid = os.fork()
+            if pid > 0:
+                # exit first parent
+                sys.exit(0)
+        except OSError, e:
+            sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
+            sys.exit(1)
+    
+        # decouple from parent environment
+        os.chdir("/")
+        os.setsid()
+        os.umask(0)
+      
+        # do second fork
+        try:
+            pid = os.fork()
+            if pid > 0:
+                # exit from second parent
+                sys.exit(0)
+        except OSError, e:
+            sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
+            sys.exit(1)
+  
+        # redirect standard file descriptors
+        sys.stdout.flush()
+        sys.stderr.flush()
+        si = file(self.stdin, 'r')
+        so = file(self.stdout, 'a+')
+        se = file(self.stderr, 'a+', 0)
+        os.dup2(si.fileno(), sys.stdin.fileno())
+        os.dup2(so.fileno(), sys.stdout.fileno())
+        os.dup2(se.fileno(), sys.stderr.fileno())
+  
+        # write pidfile
+        atexit.register(self.delpid)
+        pid = str(os.getpid())
+        file(self.pidfile,'w+').write("%s\n" % pid)
+      
+        def delpid(self):
+            os.remove(self.pidfile)
+
+        def start(self):
+            """
+            Start the daemon
+            """
+            # Check for a pidfile to see if the daemon already runs
+            try:
+                pf = file(self.pidfile,'r')
+                pid = int(pf.read().strip())
+                pf.close()
+            except IOError:
+                pid = None
+            
+            if pid:
+                message = "pidfile %s already exist. Daemon already running?\n"
+                sys.stderr.write(message % self.pidfile)
+                sys.exit(1)
+              
+            # Start the daemon
+            self.daemonize()
+            self.run()
+
+    def stop(self):
+        """
+        Stop the daemon
+        """
+        # Get the pid from the pidfile
+        try:
+            pf = file(self.pidfile,'r')
+            pid = int(pf.read().strip())
+            pf.close()
+        except IOError:
+            pid = None
+
+        if not pid:
+            message = "pidfile %s does not exist. Daemon not running?\n"
+            sys.stderr.write(message % self.pidfile)
+            return # not an error in a restart
+
+        # Try killing the daemon process       
+        try:
+            while 1:
+                os.kill(pid, SIGTERM)
+                time.sleep(0.1)
+        except OSError, err:
+            err = str(err)
+            if err.find("No such process") > 0:
+                if os.path.exists(self.pidfile):
+                    os.remove(self.pidfile)
+                else:
+                    print str(err)
+                    sys.exit(1)
+
+    def restart(self):
+        """
+        Restart the daemon
+        """
+        self.stop()
+        self.start()
+
+    def run(self):
+        """
+        You should override this method when you subclass Daemon. It will be called after the process has been
+        daemonized by start() or restart().
+        """

File src/echoserver.py

+#!/usr/bin/env python 
+
+""" 
+A simple echo server 
+""" 
+
+import socket 
+
+host = '' 
+port = 50001 
+backlog = 5 
+size = 1024 
+s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
+s.bind((host,port)) 
+s.listen(backlog)
+ 
+while True: 
+    print '1'
+    client, address = s.accept()
+    print '2' 
+    data = client.recv(size) 
+    if data:
+        if data == 'bye':
+            client.close()
+        else:
+            client.send(data)
+     
+    

File src/example.log

+DEBUG:root:This message should go to the log file
+DEBUG:root:Accepted
+DEBUG:root:File created
+DEBUG:root:Sent
+DEBUG:root:Closed
+DEBUG:root:Accepted
+DEBUG:root:File created
+DEBUG:root:Sent
+DEBUG:root:Closed
+DEBUG:root:Accepted
+DEBUG:root:File created
+DEBUG:root:Sent
+DEBUG:root:Closed
+DEBUG:root:Accepted
+DEBUG:root:File created
+DEBUG:root:Sent
+DEBUG:root:Closed
+DEBUG:root:Accepted
+DEBUG:root:File created
+DEBUG:root:Sent
+DEBUG:root:Closed
+DEBUG:root:Accepted
+DEBUG:root:File created
+DEBUG:root:Sent
+DEBUG:root:Closed
+DEBUG:root:This message should go to the log file
+DEBUG:root:Accepted
+DEBUG:root:File created
+DEBUG:root:Sent
+DEBUG:root:Closed
+DEBUG:root:Accepted
+DEBUG:root:File created
+DEBUG:root:Sent
+DEBUG:root:Closed
+DEBUG:root:Accepted
+DEBUG:root:File created
+DEBUG:root:Sent
+DEBUG:root:Closed
+DEBUG:root:Accepted
+DEBUG:root:File created
+DEBUG:root:Sent
+DEBUG:root:Closed
+DEBUG:root:Client accepted from 127.0.0.1 on 40556 port
+DEBUG:root:Client accepted from 127.0.0.1 on 39710 port
+DEBUG:root:Message: Hiiii
+
+DEBUG:root:Message: ����
+DEBUG:root:Message: ��
+DEBUG:root:Client accepted from 127.0.0.1 on 60375 port
+DEBUG:root:Message: Hello, world

File src/mydaemon.py

+#!/usr/bin/env python
+ 
+import sys, time
+from daemon import Daemon
+
+ 
+class MyDaemon(Daemon):
+    def run(self):
+        while True:
+            time.sleep(1)
+ 
+if __name__ == "__main__":
+    daemon = MyDaemon('/tmp/daemon-example.pid')
+    if len(sys.argv) == 2:
+            if 'start' == sys.argv[1]:
+                    daemon.start()
+            elif 'stop' == sys.argv[1]:
+                    daemon.stop()
+            elif 'restart' == sys.argv[1]:
+                    daemon.restart()
+            else:
+                    print "Unknown command"
+                    sys.exit(2)
+            sys.exit(0)
+    else:
+            print "usage: %s start|stop|restart" % sys.argv[0]
+            sys.exit(2)

File src/pyserver.py

+#-*- coding: utf-8 -*-
+
+import socket
+import logging
+
+
+LOG_FILENAME = 'example.log'
+logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
+logging.debug('This message should go to the log file')
+
+"""
+# create logger
+logger = logging.getLogger("simple_example")
+logger.setLevel(logging.DEBUG)
+# create console handler and set level to debug
+ch = logging.StreamHandler()
+ch.setLevel(logging.DEBUG)
+"""
+
+host = 'localhost' 
+port = 8080
+
+c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+c.bind((host, port))
+c.listen(1)
+
+while True: 
+    csock, caddr = c.accept()
+    logging.debug('Accepted') 
+    cfile = csock.makefile('rw', 0)
+    logging.debug('File created')
+    line = cfile.readline().strip()
+    
+    cfile.write('HTTP/1.0 200 OK\n\n') 
+    cfile.write('<html><head><title>Welcome %s!</title></head>' %(str(caddr))) 
+    cfile.write('<body><h1>Follow the link...</h1>') 
+    cfile.write('All the server needs to do is ') 
+    cfile.write('to deliver the text to the socket. ') 
+    cfile.write('It delivers the HTML code for a link, ') 
+    cfile.write('and the web browser converts it. <br><br><br><br>') 
+    cfile.write('<font size="7"><center> <a href="http://python.about.com/index.html">Click me!</a> </center></font>') 
+    cfile.write('<br><br>The wording of your request was: "%s"' %(line)) 
+    cfile.write('</body></html>')
+    logging.debug('Sent')    
+    
+    cfile.close() 
+    csock.close()
+    logging.debug('Closed') 

File src/selectecho.py

+#!/usr/bin/env python 
+
+""" 
+An echo server that uses select to handle multiple clients at a time. 
+Entering any line of input at the terminal will exit the server. 
+""" 
+
+import logging
+import select 
+import socket 
+import sys 
+
+LOG_FILENAME = 'example.log'
+logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
+
+host = '' 
+port = 50000
+backlog = 5 
+size = 1024 
+server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
+server.bind((host,port))
+server.listen(backlog)
+input = [server, sys.stdin]
+
+while True:
+    inputready,outputready,exceptready = select.select(input,[],[])
+
+    for s in inputready:
+        if s == server:
+            # handle the server socket
+            client, address = server.accept()
+            logging.debug("Client accepted from %s on %d port" % (address[0], address[1]))
+            input.append(client) 
+
+        elif s == sys.stdin: 
+            # handle standard input 
+            junk = sys.stdin.readline() 
+            running = 0 
+
+        else: 
+            # handle all other sockets 
+            data = s.recv(size) 
+            if data:
+                logging.debug("Message: %s" % data)
+                s.send(data)
+            else:
+                s.close()
+                input.remove(s)
+server.close()

File src/selectechoclient.py

+#!/usr/bin/env python 
+
+"""
+A simple echo client
+"""
+
+import socket 
+
+host = 'localhost' 
+port = 50000 
+size = 1024 
+s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
+s.connect((host,port)) 
+s.send('Hello, world') 
+data = s.recv(size) 
+s.close()
+print 'Received:', data
+#!/usr/bin/env python
+import socket
+
+host = '' 
+port = 8080
+
+c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+
+c.bind((host, port))
+c.listen(1)
+
+while 1: 
+    csock, caddr = c.accept() 
+    cfile = csock.makefile('rw', 0)
+    line = cfile.readline().strip()
+
+    cfile.write('HTTP/1.0 200 OK\n\n') 
+    cfile.write('<html><head><title>Welcome %s!</title></head>' %(str(caddr))) 
+    cfile.write('<body><h1>Follow the link...</h1>') 
+    cfile.write('All the server needs to do is ') 
+    cfile.write('to deliver the text to the socket. ') 
+    cfile.write('It delivers the HTML code for a link, ') 
+    cfile.write('and the web browser converts it. <br><br><br><br>') 
+    cfile.write('<font size="7"><center> <a href="http://python.about.com/index.html">Click me!</a> </center></font>') 
+    cfile.write('<br><br>The wording of your request was: "%s"' %(line)) 
+    cfile.write('</body></html>')
+    cfile.close() 
+    csock.close()