进程:
感觉只是使用Process模块加以使用即可:
# -*- coding: utf-8 -*-
# data:2019-02-23 21:23
# user:DIY
# file:thread_master.py
from socket import *
from multiprocessing import Process
from time import sleep
def dealWithClient(newSocket,destAddr):
while True:
recvData = newSocket.recv(1024)
if recvData:
print('recv[%s]:[%s]' %(str(destAddr),recvData.decode()))
else:
print('[%s]客户端已经关闭'%(str(destAddr)))
break
newSocket.close()
def main():
serSocket = socket(AF_INET,SOCK_STREAM)
serSocket.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
localAddr = ('',7788)
serSocket.bind(localAddr)
serSocket.listen(5)
try:
while True:
print('----主进程等待新客户端的到来---')
newSocket,destAddr = serSocket.accept()
print('---主进程接来下创建一个新的进程负责数据处理数据[%s]' %str(destAddr))
client = Process(target=dealWithClient,args=(newSocket,destAddr))
client.start()
newSocket.close()
finally:
serSocket.close()
if __name__ == '__main__':
main()
线程感觉只是使用Thread模块加以使用即可:
# -*- coding: utf-8 -*-
# data:2019-02-24 7:47
# user:DIY
# file:Thread_master.py
from socket import *
from threading import Thread
from time import sleep
def dealWithClient(newSocket,destAddr):
while True:
recvData = newSocket.recv(1024)
if recvData:
print('recv[%s]:[%s]' %(str(destAddr),recvData.decode()))
else:
print('[%s]客户端已经关闭'%(str(destAddr)))
break
newSocket.close()
def main():
serSocket = socket(AF_INET,SOCK_STREAM)
serSocket.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
localAddr = ('',7788)
serSocket.bind(localAddr)
serSocket.listen(5)
try:
while True:
print('----主进程等待新客户端的到来---')
newSocket,destAddr = serSocket.accept()
print('---主进程接来下创建一个新的进程负责数据处理数据[%s]' %str(destAddr))
client = Thread(target=dealWithClient,args=(newSocket,destAddr))
client.start()
# newSocket.close()
finally:
serSocket.close()
if __name__ == '__main__':
main()
协程感觉只是使用monkey和gevent模块加以使用即可:
# -*- coding: utf-8 -*-
# data:2019-02-24 9:13
# user:DIY
# file:yield_协程.py
import sys,time,gevent
from gevent import socket,monkey monkey.patch_all()
def handel_request(conn):
while True:
data = conn.recv(1024)
time.sleep(5)
if not data:
print('[%s]连接断开' % conn)
conn.close()
break
print('recv',data.decode())
def server(port):
s = socket.socket()
s.bind(('127.0.0.1',port))
s.listen(5)
while True:
cli,add = s.accept()
gevent.spawn(handel_request,cli) if __name__ == '__main__':
server(8080)