## 客户端
import socket
import gevent
import threading
import multiprocessing
ip_bind = ('127.0.0.1',8000)
c=socket.socket()
c.connect(ip_bind)
def f(n):
while True:
data=str(n)
c.send(bytes(data,encoding='utf8'))
data = c.recv(1024)
print('服务端:',str(data,encoding='utf8'))
c.close()
x=[]
if __name__ == '__main__':
v=[]
#多线程实现并发客户端
# u=[]
# for i in range(100):
# p = threading.Thread(target=f, args=[str(i), ])
# p.start()
# u.append(p)
#
# for p in u:
# p.join()
# 多进程实现并发客户端
for i in range(100):
p = multiprocessing.Process(target=f,args=[i,])
p.start()
v.append(p)
for p in v:
p.join()
## 服务端
import sys
import time
import gevent
from gevent import socket
from gevent import monkey
monkey.patch_all()
#类似于Python中的黑魔法,把很多模块的阻塞的变成非阻塞的,
#比如socket中的rece 和send 都变
#所以,为了不阻塞
def server(port):
s=socket.socket()
s.bind(('127.0.0.1',port))
s.listen(2000)
while True:
cli,add=s.accept()
gevent.spawn(handle_request,cli)
#通过gevent的启动一个协程,把客户端的socket对象传进去
def handle_request(s):
try:
while True:
data=s.recv(1024)
print('收到的信息:',str(data,encoding='utf8'))
s.send(data)
if not data:
s.shutdown(socket.SHUT_WR)
#把和客户端的这个链接销毁。
except Exception as ex:
print(ex)
finally:
s.close()
if __name__ == '__main__':
server(8000)