Socket


import socket


"""UDP 示例"""
"""服务端"""
host = ('192.168.0.50', 8080)

sock = socket.socket(socket.AF_INET, type=socket.SOCK_DGRAM)
sock.bind(host)

while True:
    data, addr = sock.recvfrom(1024)
    print(data.decode('utf-8'))
    sock.sendto(data, addr)
sock.close()

"""客户端"""
host = ('192.168.0.50', 8080)
sock = socket.socket(socket.AF_INET, type=socket.SOCK_DGRAM)
while True:
    data = input('>>')
    sock.sendto(data.encode(), host)
    rev_data, addr = sock.recvfrom(1024)
    print(rev_data.decode('utf-8'))
sock.close()


"""TCP示例"""

"""服务端"""
host = ('192.168.0.50', 8080)

sock = socket.socket()
sock.bind(host)
sock.listen(5)

while True:
    conn, addr = sock.accept()
    while True:
        data = conn.recv(1024)
        if data:
            print(data.decode('utf-8'))
            conn.sendall(data)
        else:
            print('没收到')
    conn.close()

""" 客户端 """

host = ('192.168.0.50', 8080)

sock = socket.socket()
sock.connect(host)

while True:
    data = input('>>')
    sock.sendall(data.encode())
    recv_data = sock.recv(1024)
    print(recv_data.decode('utf-8'))
    conn.close()

""" WSGI """

from wsgiref.simple_server import make_server, demo_app

with make_server('', 8000, demo_app) as httpd:
    print("Serving HTTP on port 8000...")

    # Respond to requests until process is killed
    httpd.serve_forever()

    # Alternative: serve one request, then exit
    httpd.handle_request()

更多内容请参考:
51CTO学院Python微职位-web基础1


最后更新于:2018-06-25 22:26:54