Python Web

Python入门教程: Socket底层作为web服务器

2017-12-15  本文已影响8人  破旧的大卡车

本节我直接进入Web编程. 我们将写一个python版的web服务器, 使得用户输入一个数字(例如8), 返回给用户圆周率$\pi$的前8位. 此外要求做到:

效果见图:


mserver.png

Python源码如下

#!/usr/bin env python

# This is mserver.py
# which can server multiple client at the same time
# use the thread, see 
# https://stackoverflow.com/a/40351010/1910004

# run the server: python mserver.py
# test with telnet( apt-cyg install inetutils )
#   telnet localhost 8000

import socket
import thread
# need pip install mpmath
from mpmath import mp
def Show_Pi( digits ):
    response = ''
    if  digits.isdigit() and digits >= 0:
        # Compute last digits of pi
        response = 'The first '+ str(digits) + ' digits of pi are: \r\n'
        mp.dps = digits 
        response +=  str( mp.pi )
    else:
        response = 'Your input is: ' + digits + '\r\n'
        response += 'Please input a number!'
    response += '\r\n' # start new line at the client
    return response

def New_Client( clientsocket, addr ):
    while True:
        msg = clientsocket.recv( 1024 )[:-2] #remove the \r\n
        if not msg: break
        print( addr, ' >> ',  msg  )
        clientsocket.send( Show_Pi( msg ) )
    clientsocket.close()

# Create a socket object
s = socket.socket()
host = 'localhost' #socket.gethostname()
port = 8000

print( 'Server started on :' + socket.gethostname() )
print( 'Waiting for clients...' )
# Bind to the port
s.bind( ( host, port ) )
# Wait for client connection
s.listen( 5 )

while True:
    # Establish connection with client
    c, addr = s.accept()
    print( 'Got connection from', addr )
    thread.start_new_thread( New_Client, ( c, addr ) )
s.close()
上一篇 下一篇

猜你喜欢

热点阅读