SocketServer包对socket包进行了包装(封装),使得创建socket服务非常简单。
TCPServer+BaseRequestHandler
使用TCPServer和BaseRequestHandler编写socket服务的样例。
[python]
#-*- coding:utf-8 -*-
from SocketServer import TCPServer, BaseRequestHandler
import traceback
class MyBaseRequestHandlerr(BaseRequestHandler):
"""
#从BaseRequestHandler继承,并重写handle方法
"""
def handle(self):
#循环监听(读取)来自客户端的数据
while True:
#当客户端主动断开连接时,self.recv(1024)会抛出异常
try:
#一次读取1024字节,并去除两端的空白字符(包括空格,TAB,\r,\n)
data = self.request.recv(1024).strip()
#self.client_address是客户端的连接(host, port)的元组
print "receive from (%r):%r" % (self.client_address, data)
#转换成大写后写回(发生到)客户端
self.request.sendall(data.upper())
except:
traceback.print_exc()
break
if __name__ == "__main__":
#telnet 127.0.0.1 9999
host = "" #主机名,可以是ip,像localhost的主机名,或""
port = 9999 #端口
addr = (host, port)
#购置TCPServer对象,
server = TCPServer(addr, MyBaseRequestHandlerr)
#启动服务监听
server.serve_forever()
TCPServer+StreamRequestHandler
使用TCPServer和StreamRequestHandler编写socket服务的样例。StreamRequestHandler从BaseRequestHandler,并做了封装,使得读写数据更容易。
[python]
#-*- coding:utf-8 -*-
from SocketServer import TCPServer, StreamRequestHandler
import traceback
class MyStreamRequestHandlerr(StreamRequestHandler):
"""
#继承StreamRequestHandler,并重写handle方法
#(StreamRequestHandler继承自BaseRequestHandler)
"""
def handle(self):
while True:
#客户端主动断开连接时,self.rfile.readline()会抛出异常
try:
#self.rfile类型是socket._fileobject,读写模式是"rb",方法有
#read,readline,readlines,write(data),writelines(list),close,flush
data = self.rfile.readline().strip()
print "receive from (%r):%r" % (self.client_address, data)
#self.wfile类型是socket._fileobject,读写模式是"wb"
self.wfile.write(data.upper())
except:
traceback.print_exc()
break
if __name__ == "__main__":
host = "" #主机名,可以是ip,像localhost的主机名,或""
port = 9999 #端口
addr = (host, port)
server = TCPServer(addr, MyStreamRequestHandlerr)
server.serve_forever()
ThreadingTCPServer+StreamRequestHandler=多线程socket
使用ThreadingTCPServer和StreamRequestHandler编写socket服务的样例。ThreadingTCPServer从ThreadingMixIn和TCPServer继承,实现多线程。
[python]
#-*- coding:utf-8 -*-
from SocketServer import ThreadingTCPServer, StreamRequestHandler
import traceback
class MyStreamRequestHandlerr(StreamRequestHandler):
def handle(self):
while True:
try:
data = self.rfile.readline().strip()
print "receive from (%r):%r" % (self.client_address, data)
self.wfile.write(data.upper())
except:
traceback.print_exc()
break
if __name__ == "__main__":
host = "" #主机名,可以是ip,像localhost的主机名,或""
port = 9999 #端口
addr = (host, port) www.2cto.com
#ThreadingTCPServer从ThreadingMixIn和TCPServer继承
#class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass
server = ThreadingTCPServer(addr, MyStreamRequestHandlerr)
server.serve_forever()
多线程socket效果:
补充:
用原始套接字多线程处理多连接
处理多个连接
为了处理多个连接,我们需要一个独立的处理代码在主服务器接收到连接时运行。一种方法是使用线程,服务器接收到连接然后创建一个线程来处理连接收发数据,然后主服务器程序返回去接收新的连接。
下面是我们使用线程来处理连接请求:
import socket
import sys
from thread import *
HOST = '' # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
#Function for handling connections. This will be used to create threads
def clientthread(conn):
#Sending message to connected client
conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string
#infinite loop so that function do not terminate and thread do not end.
while True:
#Receiving from client
data = conn.recv(1024)
reply = 'OK...' + data
if not data:
break
conn.sendall(reply)
#came out of loop
conn.close()
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
start_new_thread(clientthread ,(conn,))
s.close()
运行上述服务端程序,然后像之前一样打开三个终端窗口并执行 telent 命令:
$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Welcome to the server. Type something and hit enter
hi
OK...hi
asd
OK...asd
cv
OK...cv
服务器端所在终端窗口输出信息如下:
$ python server.py
Socket created
Socket bind complete
Socket now listening
Connected with 127.0.0.1:60730
Connected with 127.0.0.1:60731
线程接管了连接并返回相应数据给客户端。
这便是我们所要介绍的服务器端编程。