python -socket通信

一个简单的socket请求

# -*-coding:utf-8 -*-
# BY WANGCC

import socket

sock = socket.socket()
sock.bind(('127.0.0.1',8000))
sock.listen(5)

while 1:
    print("server waiting....")
    conn,addr = sock.accept()
    data = conn.recv(1024)
    print('data',data)
    conn.send(b'HTTP/1.1 200 OK \r\n\r\n hello !')
    conn.close()

这样会在8000端口生成一个监听程序,来监听来访问的请求。

简化,可以使用wsgiref 模块来来简化监听程序,这里有一个简单的小例子,可以点击查看。

# -*-coding:utf-8 -*-
# BY WANGCC

from wsgiref.simple_server import make_server

def application(environ,start_response):
    #按照http协议解析数据 environ
    #按照http协议组装数据  start_response
    print(environ)

    #当前请求路径
    path = environ.get('PATH_INFO')
    start_response('200 OK',[])
    print(path)
    if path=='/login':
        with open('login.html','r') as f:
            data = f.read()
    elif path=='/index':
        with open('index.html','r') as f:
            data = f.read()
    return [data.encode('utf8')]


#封装socket
httped = make_server("",8080,application)

#等待用户连接 conn,addr = sock.accept
httped.serve_forever()

你可能感兴趣的:(python -socket通信)