写一个基于TCP协议套接字,服务端实现接收客户端的连接并发。
多线程
#客户端
import socket
client=socket.socket()
client.connect(('127.0.0.1',8888))
# def c():
while True:
s = input('输入:')
client.send(s.encode('utf-8'))
data=client.recv(1024).decode('utf-8')
print(data)
client.close()
#服务端
import socket
from threading import Thread
def s(conn):
while True:
try:
data=conn.recv(1024).decode('utf-8')
print(data)
conn.send(data.encode('utf-8'))
except Exception as e:
print(e)
break
conn.close()
if __name__ == '__main__':
# while True:
server = socket.socket()
server.bind(('127.0.0.1', 8888))
server.listen()
while True:
conn,addr=server.accept()
t=Thread(target=s,args=(conn,))
t.start()
多进程
#客户端
import socket
client=socket.socket()
client.connect(('127.0.0.1',9999))
while True:
data=input('客户端输入:')
client.send(data.encode('utf-8'))
msg=client.recv(1024).decode('utf-8')
print(msg)
#服务端
import socket
from multiprocessing import Process
def s(conn):
while True:
try:
data=conn.recv(1024).decode('utf-8')
print(data)
conn.send(data.encode('utf-8'))
except Exception as e:
print(e)
break
conn.close()
if __name__ == '__main__':
server=socket.socket()
server.bind(('127.0.0.1',9999))
server.listen()
while True:
conn,addr=server.accept()
t=Process(target=s,args=(conn,))
t.start()