simple_echo_server.py
Go to the documentation of this file.
00001 #!/usr/bin/env python
00002 
00003 import SocketServer
00004 import sys
00005 import argparse
00006 import socket
00007 HOSTNAME = '0.0.0.0'
00008 
00009 def runTCP(host, port, buffer_size):
00010     global BUFFER_SIZE
00011     BUFFER_SIZE = buffer_size
00012     server = SocketServer.TCPServer((host, port), Handler)
00013     server.serve_forever()
00014 
00015 def printData(data):
00016     print data, 
00017     print "(%d bytes)" % sys.getsizeof(data)
00018     
00019 class Handler(SocketServer.StreamRequestHandler):
00020     def handle(self):
00021         global BUFFER_SIZE
00022         while True:
00023             data = self.request.recv(BUFFER_SIZE)
00024             printData(data)
00025             if len(data) == 0:
00026                 break
00027             #self.request.send(data)
00028         self.request.close()
00029 
00030 def runUDP(host, port, buffer_size):
00031     clientsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
00032     clientsock.bind((host, port))
00033     while True:
00034         recv_msg, addr = clientsock.recvfrom(buffer_size)
00035         printData(recv_msg)
00036 
00037     
00038 if __name__ == "__main__":
00039     parser = argparse.ArgumentParser(description='Simple socket server')
00040     parser.add_argument("--port", default=8080, type=int)
00041     parser.add_argument("--buffer-size", default=1024, type=int)
00042     parser.add_argument("--udp", action="store_true")
00043     args = parser.parse_args()
00044     
00045     if args.udp:
00046         print 'listening UDP', (HOSTNAME, args.port), "buffer size is", args.buffer_size
00047         runUDP(HOSTNAME, args.port, args.buffer_size)
00048     else:
00049         print 'listening TCP', (HOSTNAME, args.port), "buffer size is", args.buffer_size
00050         runTCP(HOSTNAME, args.port, args.buffer_size)
00051     
00052     


mini_maxwell
Author(s): Yusuke Furuta
autogenerated on Sun Jan 25 2015 12:37:43