4.24作业

利用多进程或多线程自己实现TCP服务端的并发

'''
服务端
'''

from threading import Thread
from socket import *

sever=socket(AF_INET,SOCK_STREAM)# 括号内不传参默认是TCP(AF_INET SOCK_STREAM)
sever.bind(('192.168.1.2',8888))
sever.listen(5)

def talk(conn):
    while True:
        try:
            data=conn.recv(1024)
            # if len(data)==0:break
            print(data)
            conn.send(data.upper())
        except ConnectionResetError as e:
            print(e)
            break
    conn.close()


while True:
    conn,addr=sever.accept()
    t=Thread(target=talk,args=(conn,))
    t.start()
    
    
客户端
import socket


client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect(('192.168.1.2',8888))

while 1:

    client.send(b'hello world')
    data=client.recv(1024)
    print(data.decode('utf-8'))
posted @ 2020-04-24 21:04  aksas  阅读(88)  评论(0编辑  收藏  举报