當前位置:
首頁 > 知識 > python 基礎之 socket介面與web介面

python 基礎之 socket介面與web介面

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()

python 基礎之 socket介面與web介面

打開今日頭條,查看更多圖片
喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 程序員小新人學習 的精彩文章:

Scrapy 入門教程
基於linux內核包過濾技術的應用網關

TAG:程序員小新人學習 |