建立伺服器的步驟:先建立一個request handler類通過子類化BaseRequestHandler然後重載handle()方法。然後通過傳入伺服器的位址和request handler來初始化一個服務類。最後調用handle_request()或serve_forever()來運作。
TCP:
import SocketServer
class MyTCPServer(SocketServer.BaseRequestHandler):
"""
The RequestHandler class for our server
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the client.
"""
def handle(self):
#self.request is the TCP socket connected to the client
self.data=self.request.recv(2048).strip()
print '{} wrote:'.format(self.client_address[0])
print self.data
self.request.sendall(self.data.upper())
if __name__=='__main__':
HOST,PORT='',51234
server=SocketServer.TCPServer((HOST,PORT),MyTCPServer)
server.serve_forever()
# class MyTCPServer(SocketServer.StreamRequestHandler):
# def handle(self):
#self.rfile is a file-like object created by the handler;
#we can now use e.g. readline() instead of raw recv() calls
# self.data=self.rfile.readline().strip()
# print '{} wrote:'.format(self.client_address[0])
# print self.data
#Likewise, self.wfile is a file-like object used to write back
# to the client
#
# self.wfile.write(self.data.upper())
第二個handler的readline會多次調用recv直到遇到一個換行符,而第一個handler的recv()會傳回用戶端在一個sendall()裡面發送的所有東西。
用戶端使用socket編寫的話,連接配接後隻能進行一此資料傳輸,之後便會關閉。
import SocketServer
class MyUDPServer(SocketServer.BaseRequestHandler):
"""
This class works similar to TCP handler class,except that self.request
consists of a pair of data and client socket , and since there is no
connnection the client address must be given explicitly when sending
data back via sendto()
"""
def handle(self):
data=self.request[0].strip()
sock=self.request[1]
print "{} wrote:".format(self.client_address[0])
print data
socket.sendto(data.upper(),self.client_address)
if __name__=='__main__':
HOST,PORT='',51234
server=SocketServer.UDPServer((HOST,PORT),MyUDPServer)
server.serve_forever()