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()