何謂socket
計算機,顧名思義即是用來做計算。因而也需要輸入和輸出,輸入需要計算的條件,輸出計算結果。這些輸入輸出可以抽象為I/O(input output)。
Unix的計算機處理IO是通過文件的抽象。計算機不同的進程之間也有輸入輸出,也就是通信。因此這這個通信也是通過文件的抽象文件描述符來進行。
在同一臺計算機,進程之間可以這樣通信,如果是不同的計算機呢?網絡上不同的計算機,也可以通信,那么就得使用網絡套接字(socket)。socket就是在不同計算機之間進行通信的一個抽象。他工作于TCP/IP協議中應用層和傳輸層之間的一個抽象。如下圖:

服務器通信
socket保證了不同計算機之間的通信,也就是網絡通信。對于網站,通信模型是客戶端服務器之間的通信。兩個端都建立一個socket對象,然后通過socket對象對數據進行傳輸。通常服務器處于一個無線循環,等待客戶端連接:

socket 通信實例
socket接口是操作系統提供的,調用操作系統的接口。當然高級語言一般也封裝了好用的函數接口,下面用python代碼寫一個簡單的socket服務端例子:
server.py
import socketHOST = 'localhost' # 服務器主機地址PORT = 5000 # 服務器監聽端口BUFFER_SIZE = 2048 # 讀取數據大小# 創建一個套接字sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 綁定主機和端口sock.bind((HOST, PORT))# 開啟socket監聽sock.listen(5)print 'Server start, listening {}'.format(PORT)while True: # 建立連接,連接為建立的時候阻塞 conn, addr = sock.accept() while True: # 讀取數據,數據還沒到來阻塞 data = conn.recv(BUFFER_SIZE) if len(data): print 'Server Recv Data: {}'.format(data) conn.send(data) print 'Server Send Data: {}'.format(data) else: print 'Server Recv Over' break conn.close()sock.close()client.py
import socketHOST = 'localhost'PORT = 5000BUFFER_SIZE = 1024# 創建客戶端套接字sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# 連接到服務器sock.connect((HOST, PORT))try: message = "Hello" # 發起數據給服務器 sock.sendall(message) amount_received = 0 amount_expected = len(message) while amount_received < amount_expected: # 接收服務器返回的數據 data = sock.recv(10) amount_received += len(data) print 'Client Received: {}'.format(data)except socket.errno, e: print 'Socket error: {}'.format(e)except Exception, e: print 'Other exception: %s'.format(e)finally: print 'Closing connection to the server' sock.close()TCP 三次握手
python代碼寫套接字很簡單。傳說的TCP三次握手又是如何體現的呢?什么是三次握手呢?
第一握:首先客戶端發送一個syn,請求連接,
第二握:服務器收到之后確認,并發送一個 syn ack應答
第三握:客戶端接收到服務器發來的應答之后再給服務器發送建立連接的確定。
用下面的比喻就是
C:約么?
S:約
C:好的
約會
這樣就建立了一個TCP連接會話。如果是要斷開連接,大致過程是:

上圖也很清晰的表明了三次握手的socket具體過程。
至此,客戶端和服務器的socket通信連接建立完成,剩下的就是兩個端的連接對象收發數據,從而完成網絡通信。
SimpleHTTPServer
構建一個簡單的HTTP服務,需要繼承HTTPServer,同時requesthandler也需要繼承BaseHTTPRequestHandler。python已經實現了一個例子,那就是SimpleHTTPServer。因此分析SimpleHTTPServer來查看如何使用前面的一些類構建http服務。
曾經為了表示python的簡潔優雅,經常會舉這樣的例子,python可以一行代碼開啟一個服務器。
$ python -m SimpleHTTPServer
這里的SimpleHTTPServer就是實現了HTTPServer的模塊。
SimpleHTTPServer通過調用BaseHTTPServer模塊的test方法做為入口。
def test(HandlerClass = SimpleHTTPRequestHandler, ServerClass = BaseHTTPServer.HTTPServer): BaseHTTPServer.test(HandlerClass, ServerClass)
test方法做了兩件事,第一件就是使用HTTPServer接受一個監聽地址和requestClass參數,創建了一個實例對象,調用server_forever方法開啟服務。
1.SimpleHTTPRequestHandler
根據之前的分析,使用httpserver的服務,我們只需要繼續BaseHTTPRequestHandler,并提供自省的method方法即可。
class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): server_version = "SimpleHTTP/" + __version__ def do_GET(self): f = self.send_head() if f: self.copyfile(f, self.wfile) f.close() def do_HEAD(self): f = self.send_head() if f: f.close()
do_GET 和 do_HEAD 分別實現了http的get請求和head請求的處理。他們調用send_head方法:
def send_head(self): path = self.translate_path(self.path) f = None if os.path.isdir(path): if not self.path.endswith('/'): self.send_response(301) self.send_header("Location", self.path + "/") self.end_headers() return None for index in "index.html", "index.htm": index = os.path.join(path, index) if os.path.exists(index): path = index break else: return self.list_directory(path) ctype = self.guess_type(path) try: f = open(path, 'rb') except IOError: self.send_error(404, "File not found") return None self.send_response(200) self.send_header("Content-type", ctype) fs = os.fstat(f.fileno()) self.send_header("Content-Length", str(fs[6])) self.send_header("Last-Modified", self.date_time_string(fs.st_mtime)) self.end_headers() return fsend_head 方法通過uri的path分析得到客戶請求的網路路徑。構造head的mime元信息并發送到客戶端,然后返回一個打開path的文件句柄。
2.copyfile
do_GET的下一步就是通過 copyfile方法,將客戶請求的path的文件數據寫入到緩沖可寫文件中,發送給客戶端。
3.list_directory
SimpleHTTPServer模塊還提供了list_directory方法,用于響應path是一個目錄,而不是文件的情況。
def list_directory(self, path): try: list = os.listdir(path) except os.error: self.send_error(404, "No permission to list directory") return None list.sort(key=lambda a: a.lower()) f = StringIO() displaypath = cgi.escape(urllib.unquote(self.path)) f.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">') f.write("<html>/n<title>Directory listing for %s</title>/n" % displaypath) f.write("<body>/n<h2>Directory listing for %s</h2>/n" % displaypath) f.write("<hr>/n<ul>/n") for name in list: fullname = os.path.join(path, name) displayname = linkname = name # Append / for directories or @ for symbolic links if os.path.isdir(fullname): displayname = name + "/" linkname = name + "/" if os.path.islink(fullname): displayname = name + "@" # Note: a link to a directory displays with @ and links with / f.write('<li><a href="%s">%s</a>/n' % (urllib.quote(linkname), cgi.escape(displayname))) f.write("</ul>/n<hr>/n</body>/n</html>/n") length = f.tell() f.seek(0) self.send_response(200) encoding = sys.getfilesystemencoding() self.send_header("Content-type", "text/html; charset=%s" % encoding) self.send_header("Content-Length", str(length)) self.end_headers() return f由此可見,處理客戶端的請求,只需要使用 send_reponse, send_header 和 end_headers ,就能向客戶端發送reponse。
4.自定義http服務
定義一個CustomHTTPRequestHadnler繼承自BaseHTTPRequestHandler。在其內實現do_GET 方法來處理get請求。
然后再定義一個CustomHTTPServer繼承自HTTPServer,它接受CustomHTTPRequestHadnler作為自己的handler。簡單的代碼如下:
# -*- coding: utf-8 -*-from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServerclass CustomHTTPRequestHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write("hello world/r/n")class CustomHTTPServer(HTTPServer): def __init__(self, host, port): HTTPServer.__init__(self, (host, port), CustomHTTPRequestHandler)def main(): server = CustomHTTPServer('127.0.0.1', 8000) server.serve_forever()if __name__ == '__main__': main()使用curl訪問可以得到
➜ ~ curl http://127.0.0.1:8000hello world➜ ~
控制臺會打出訪問的log。
127.0.0.1 - - [01/Jun/2015 11:42:33] "GET / HTTP/1.1" 200 -
從socket的建立,select的IO模式,再到Server和Handler的組合構建服務。我們已經熟悉了python的基本網絡編程。python的web開發中,更多是使用WSGI協議。實現該協議的還有 uWSGI和gunicorn等庫。相比那些庫,python內部提供了一個wsgiref模塊,實現了一個簡單wsgi服務--simple_server。
接下來將會通過分析simple_server,更好的掌握WSGI協議。
新聞熱點
疑難解答
圖片精選