Echo Server


In [1]:
import socket
import sys
host = 'localhost'
backlog = 50
def echo_server(port):
    """simple echo server"""
    # Create a TCP socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # Enable reuse address/port
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # Bind the socket to the port
    server_address = (host, port)
    print "Starting up echo server on %s port %s" % server_address
    sock.bind(server_address)
    # Listen to clients, backlog argument specifies the max no. of queued connections
    sock.listen(backlog)

    while True:
        print "Waiting to receive message from client"
        client, address = sock.accept()
        data = client.recv(2048)
        if data:
            print "Data: %s" % data
            client.send(data)
            print "Send %s bytes back to %s" % (data, address)
            if data == 'bye':
                print "echo server stop"
                break
        # End connection
        client.close()
echo_server(9999)


Starting up echo server on localhost port 9999
Waiting to receive message from client
Data: Test message. This will be echoed1111.
Send Test message. This will be echoed1111. bytes back to ('127.0.0.1', 56795)
Waiting to receive message from client
Data: Test message. This will be echoed1111.
Send Test message. This will be echoed1111. bytes back to ('127.0.0.1', 56806)
Waiting to receive message from client
Data: bye
Send bye bytes back to ('127.0.0.1', 56821)
echo server stop

File Transfer


In [2]:
import socket
import sys
host = 'localhost'
backlog = 50
def file_server(port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_address = (host, port)
    print "Starting up file server on %s port %s" % server_address
    sock.bind(server_address)
    sock.listen(backlog)
    while True:
        print "Waiting to receive file from client"
        client, address = sock.accept()
        data = client.recv(2048)
        if data:
            print 'received file'
            with open('ft_test_server.txt', 'w') as fp:
                fp.write(data)
            break
        # End connection
        client.close()
    print "service closed"
file_server(9999)


Starting up file server on localhost port 9999
Waiting to receive file from client
received file
service closed

UDP Server


In [1]:
import socket  
  
address = ('127.0.0.1', 31500)  
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  
s.bind(address)  
  
while True:  
    data, addr = s.recvfrom(2048)  
    if not data:  
        print "client has exist"  
        break
    print "received:", data, "from", addr
    if data:
        if data == 'exit':
            print 'exiting server'
            break
  
s.close()


received: a from ('127.0.0.1', 61823)
received: b from ('127.0.0.1', 61823)
received: fsdfsafd from ('127.0.0.1', 61823)
received: exit from ('127.0.0.1', 61823)
exiting server

FTP Server


In [ ]:
import os
from pyftpdlib.authorizers import DummyAuthorizer  
from pyftpdlib.handlers import FTPHandler  
from pyftpdlib.servers import FTPServer  
  
def ftp_server():  
    # Instantiate a dummy authorizer for managing 'virtual' users  
    authorizer = DummyAuthorizer()  
  
    # Define a new user having full r/w permissions and a read-only  
    # anonymous user  
    authorizer.add_user('user', '12345', '.', perm='elradfmwM')  
    authorizer.add_anonymous(os.getcwd())  
  
    # Instantiate FTP handler class  
    handler = FTPHandler  
    handler.authorizer = authorizer  
  
    # Define a customized banner (string returned when client connects)  
    handler.banner = "customized based ftpd ready."  
  
    # Specify a masquerade address and the range of ports to use for  
    # passive connections.  Decomment in case you're behind a NAT.  
    #handler.masquerade_address = '151.25.42.11'  
    #handler.passive_ports = range(60000, 65535)  
  
    # Instantiate FTP server class and listen on 0.0.0.0:2121  
    address = ('0.0.0.0', 2121)  
    server = FTPServer(address, handler)  
  
    # set a limit for connections  
    server.max_cons = 256  
    server.max_cons_per_ip = 5  
  
    # start ftp server  
    server.serve_forever()  
  
ftp_server()

XMLRPC


In [ ]:
from SimpleXMLRPCServer import SimpleXMLRPCServer
def is_even(n):
    return n%2 == 0
server = SimpleXMLRPCServer(("localhost", 8000))#确定URL和端口
print "Listening on port 8000..."
server.register_function(is_even, "is_even") #注册is_even函数
server.serve_forever()#启动服务器,并使其对这个连接可用

In [ ]:
from SimpleXMLRPCServer import SimpleXMLRPCServer  
global a  
import ast  
from cStringIO import StringIO  
from numpy.lib import format  
import numpy  
  
class T:  
    def to_string(self,arr):  
        f = StringIO()  
        if type(arr)==numpy.ndarray:  
            format.write_array(f,arr)  
            s = f.getvalue()  
        elif isinstance(arr,str)==False:  
            s = str(arr)  
        return s  
  
    def from_string(self,s):  
        if s[0]!="[": # converted from numpy array  
            f = StringIO(s)  
            arr = format.read_array(f)  
        else:  
            arr = ast.literal_eval(s)  
        return arr  
  
    def load(self):  
        global a  
        a = [1 ,2, 24]  
        return a  
  
    def ret_a(self):  
        global a  
        return a  
          
  
  
server = SimpleXMLRPCServer(("localhost", 8002))  
server.register_instance(T())  
srv = T()  
srv.load()  
server.serve_forever()

In [ ]:
from SimpleXMLRPCServer import SimpleXMLRPCServer
import xmlrpclib
def logo():
   handle = open("logo.jpg",'rb')
   return xmlrpclib.Binary(handle.read())
   handle.close()
server = SimpleXMLRPCServer(("localhost", 9999))
print "Listening on port 8000..."
server.register_function(logo, 'logo')
server.serve_forever()


Listening on port 8000...

In [ ]: