Tiny_Lu
不忘初心

Day 29 作业/服务端实现接收客户端的连接并发

"""
服务端:
    1.有固定的IP和PORT
    2.24小时不间断提供服务
    3.能够支持并发
"""
server = socket.socket()

server.bind((
    '127.0.0.1', 9550
))

server.listen(5)
print('启动服务端。。。')


def working(conn):
    while True:
        try:
            data = conn.recv(1024)
            if len(data) == 0:
                break
            print(data.decode('utf-8'))
            time.sleep(1)
            conn.send(data.upper())

        except Exception as e:
            print(e)
            break

    conn.close()


while True:
    conn, addr = server.accept()
    print(addr)
    # 这里实现并发
    t = Thread(target=working, args=(conn,))
    t.start()
# 客户端
import socket
from threading import Thread


client = socket.socket()

client.connect(
    ('127.0.0.1', 8080)
)


def task(i):
    while True:
        msg = f'线程{i}'
        client.send(msg.encode('utf8'))
        data = client.recv(1024).decode('utf8')
        print(data)


if __name__ == '__main__':
        p = Thread(target=task, args=(i, ))
        p.start()
posted @ 2019-10-22 19:18  二二二二白、  阅读(93)  评论(0编辑  收藏  举报