多线程并发简单版
server-------------------
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2018/6/19 9:33
# @File : server1.py
# from socket import *
# from threading import Thread
#
#
# def communicate(conn):
# while True:
# try:
# data = conn.recv(1024)
# if not data:break
# conn.send(data.upper())
# except ConnectionResetError:
# break
# conn.close()
#
#
# def server(ip, port):
# server = socket(AF_INET, SOCK_STREAM)
# server.bind((ip, port))
# server.listen(5)
#
# while True:
# conn, addr = server.accept() # 建立连接
# t = Thread(target=communicate, args=(conn, ))
# t.start()
#
# server.close()
#
#
# if __name__ == '__main__':
# server('127.0.0.1', 8080)
# 基于线程池实现
from socket import *
from concurrent.futures import ThreadPoolExecutor
def communicate(conn):
while True:
try:
data = conn.recv(1024)
if not data:break
conn.send(data.upper())
except ConnectionResetError:
break
conn.close()
def server(ip, port):
server = socket(AF_INET, SOCK_STREAM)
server.bind((ip, port))
server.listen(5)
while True:
conn, addr = server.accept() # 建立连接
pool.submit(communicate, conn)
server.close()
if __name__ == '__main__':
pool = ThreadPoolExecutor(2) # 不要设置超过机器范围,2个不支持3个
server('127.0.0.1', 8080)
client--------------------
# 可以右键启动多个
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2018/6/19 9:33
# @File : client1.py
# 右键运行一次就是一个进程
from socket import *
client = socket(AF_INET, SOCK_STREAM)
client.connect(('127.0.0.1', 8080))
while True:
msg = input('>>>:').strip()
if not msg:continue
client.send(msg.encode('utf-8'))
data = client.recv(1024)
print(data.decode('utf-8'))
client.close()