本文主要介紹使用
Python語言編寫Socket協(xié)議Server及Client的簡單實(shí)現(xiàn)方法。
1. Python Socket編程簡介
Socket通常也稱作"套接字",應(yīng)用程序通常通過"套接字"向網(wǎng)絡(luò)發(fā)出請求或者應(yīng)答網(wǎng)絡(luò)請求。
三種流行的套接字類型是:stream,datagram和raw。stream和datagram套接字可以直接與TCP協(xié)議進(jìn)行接口,而raw套接字則接口到IP協(xié)議。
Python Socket模塊提供了對低層BSD套接字樣式網(wǎng)絡(luò)的訪問,使用該模塊建立具有TCP和流套接字的簡單服務(wù)器。詳見https://docs.python.org/2/library/socket.html
2. Python Socket Server
實(shí)現(xiàn)代碼如下
# -*- coding:utf-8 -*- from socket import * def SocketServer(): try: Colon = ServerUrl.find(':') IP = ServerUrl[0:Colon] Port = int(ServerUrl[Colon+1:]) #建立socket對象 print 'Server start:%s'%ServerUrl sockobj = socket(AF_INET, SOCK_STREAM) sockobj.setsockopt(SOL_SOCKET,SO_REUSEADDR, 1) #綁定IP端口號 sockobj.bind((IP, Port)) #監(jiān)聽,允許5個(gè)連結(jié) sockobj.listen(5) #直到進(jìn)程結(jié)束時(shí)才結(jié)束循環(huán) while True: #等待client連結(jié) connection, address = sockobj.accept( ) print 'Server connected by client:', address while True: #讀取Client消息包內(nèi)容 data = connection.recv(1024) #如果沒有data,跳出循環(huán) if not data: break #發(fā)送回復(fù)至Client RES='200 OK' connection.send(RES) print 'Receive MSG:%s'%data.strip() print 'Send RES:%s\r\n'%RES #關(guān)閉Socket connection.close( ) except Exception,ex: print ex ServerUrl = "192.168.16.15:9999" SocketServer() |
注:需要注意的是Socket對象建立后需要加上sockobj.setsockopt(SOL_SOCKET,SO_REUSEADDR, 1),否則會(huì)出現(xiàn)Python腳本重啟后Socket Server端口不會(huì)立刻關(guān)閉,出現(xiàn)端口占用錯(cuò)誤。
3. Python Socket Client
實(shí)現(xiàn)代碼如下
# -*- coding:utf-8 -*- from socket import * def SocketClient(): try: #建立socket對象 s=socket(AF_INET,SOCK_STREAM,0) Colon = ServerUrl.find(':') IP = ServerUrl[0:Colon] Port = ServerUrl[Colon+1:] #建立連接 s.connect((IP,int(Port))) sdata='GET /Test HTTP/1.1\r\n\ Host: %s\r\n\r\n'%ServerUrl print "Request:\r\n%s\r\n"%sdata s.send(sdata) sresult=s.recv(1024) print "Response:\r\n%s\r\n" %sresult #關(guān)閉Socket s.close() except Exception,ex: print ex ServerUrl = "192.168.16.15:9999" SocketClient() |
4. 運(yùn)行結(jié)果
Socket Server端運(yùn)行截圖如下:
Socket-Server
Socket Client端運(yùn)行截圖如下: