python 网络编程 主要有socket模块、BaseHTTPServer模块。socket属于更底层次,方便在日常运维工作中使用, http web接口更适合开放给外部人员使用,毕竟大多数语言都很方便支持http请求。

首先看最基本socket客户端与服务端实例:

#!/usr/bin/python
#coding=utf-8
import socket
host = 'xx'
socketport = '1009'
flag = 'xxxx'

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, int(socketport)))
sock.send(flag)
recv = sock.recv(1024)
print "接收终端返回码:"+recv
sock.close()
#!/usr/bin/python
#coding=utf-8
import os
import sys
import commands
import traceback
import socket
reload(sys)
sys.setdefaultencoding('utf8')

def oscmd(buf):
    cmdtype = buf.strip()
    ##业务逻辑代码、处理完毕返回给客端#
    connection.send('sucess')

# Step1: 创建socket对象
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 让socket支持地址复用 默认是不支持的
sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
# Step2: 配置socket  绑定IP和端口  
sock.bind(('0.0.0.0', 1009))
# 设置最大允许连接数,各连接和server的通信遵循FIFO原则 
sock.listen(1)

# Step3: 循环轮询socket状态,等待访问 
while 1:
    try:
        #获取连接
        connection,address = sock.accept()
        buf = connection.recv(10240)
        src_ip = address[0]
        src_port = str(address[1])
        print "接收提交请求:["+ buf +"] 发送源:["+ src_ip +":"+ src_port+"]"
        # Step4:处理请求数据,验证更新key,录入更新任务,返回处理结果
        oscmd(buf)
    except (KeyboardInterrupt, SystemExit):
        print "链接错误,请检查!"
        raise Exception

 

socket多线程,同时并发处理多个请求。加入了python多线程而已

def handle_connection(conn,addr)


def main():
    # socket.AF_INET    用于服务器与服务器之间的网络通信
    # socket.SOCK_STREAM    基于TCP的流式socket通信
    serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 设置端口可复用,保证我们每次Ctrl C之后,快速再次重启
    serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    serversocket.bind(('192.168.2.221', 10089))
    # 可参考:https://stackoverflow.com/questions/2444459/python-sock-listen
    serversocket.listen(5)
    try:
        while True:
            conn,addr = serversocket.accept()
            t = threading.Thread(target=handle_connection, args=(conn,addr))
            t.start()
    finally:
        serversocket.close()

 

web接口客户端与服务端实例、服务端支持GET与POST请求

get请求
curl 192.168.11.xx:1009/api
post请求(json格式)
curl localhost:9999/api/daizhige/article -X POST -H "Content-Type:application/json" -d '"title":"comewords","content":"articleContent"'
#!/usr/bin/python
#encoding=utf-8
'''
基于BaseHTTPServer的http server实现,包括get,post方法,get参数接收,post参数接收。
'''
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import io,shutil
import urllib
import os, sys
import commands

class MyRequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        mpath,margs=urllib.splitquery(self.path) 
        self.do_action(mpath,margs)
    def do_POST(self):
        mpath,margs=urllib.splitquery(self.path)
        datas = self.rfile.read(int(self.headers['content-length']))
        self.do_action(mpath, datas)

    def do_action(self,args):
            self.outputtxt( args )

    def outputtxt(self, content):
        #指定返回编码
        enc = "UTF-8"
        content = content.encode(enc)
        f = io.BytesIO()
        f.write(content)
        f.seek(0)
        self.send_response(200)
        self.send_header("Content-type", "text/html; charset=%s" % enc)
        self.send_header("Content-Length", str(len(content)))
        self.end_headers()
        shutil.copyfileobj(f,self.wfile)

def main():
    try:
        server = HTTPServer(('192.168.xx.219',1009),MyRequestHandler)
        print 'welcome to websocket'
        server.serve_forever()
    except KeyboardInterrupt:
        print 'shutting down server'
        server.socket.close()
if __name__ == '__main__':
    main()

 

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐