【Python】阻塞模型

from socket import *


class Server(object):
def __init__(self, ip_bind=('127.0.0.1', 8080)):
self.head_buffer = 1024
self.coding = 'utf-8'
self.server = socket(AF_INET, SOCK_STREAM)
self.server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
self.server.bind(ip_bind)
self.server.listen(50)
self.server.setblocking(True) # 默认就是True 基于阻塞模型IO

def run(self):
while 1:
try:
conn, address_link = self.server.accept()
self.talk(conn)
except ConnectionResetError:
break
self.server.close()

def talk(self, conn):
while 1:
try:
repo = conn.recv(self.head_buffer)
if not repo: break
data = repo.decode(self.coding)
conn.send(data.upper().encode(self.coding))
except ConnectionResetError:
break
conn.close()
posted @ 2018-08-26 18:07  caya  阅读(169)  评论(0编辑  收藏  举报