Python Socket多线程并发原理及实现
作者:看雪。 时间:2022-09-05 08:21:07
1.SocketServer模块编写的TCP服务器端代码
Socketserver原理图
服务端:
import SocketServer #导入SocketServer,多线程并发由此类实现
class MySockServer(SocketServer.BaseRequestHandler): #定义一个类
def handle(self): #handle(self)方法是必须要定义的,可以看上面的说明
print 'Got a new connection from', self.client_address
while True:
data = self.request.recv(1024) #需要通过self的方法调用数据接收函数
if not data:break
print 'recv:', data
self.request.send(data.upper()) #需要通过self的方法调用数据接收函数
if __name__ == '__main__': #并非一定要用这样的方式,只是建议这样使用
HOST = '' #定义侦听本地地址口(多个IP地址情况下),这里表示侦听所有
PORT = 50007 #Server端开放的服务端口
s = SocketServer.ThreadingTCPServer((HOST, PORT), MySockServer)
#调用SocketServer模块的多线程并发函数
s.serve_forever() #持续接受客户端的连接
客户端:
import socket
HOST = '192.168.1.13'
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
while True:
user_input = raw_input('msg to send:').strip()
s.sendall(user_input)
data = s.recv(1024)
print 'Received', repr(data)
s.close()
2.基于Python Socketserver的实现的FTP程序
服务端:
import socketserver
import struct
import json
import os
class FtpServer(socketserver.BaseRequestHandler):
coding='utf-8'
server_dir='file_upload'
max_packet_size=1024
BASE_DIR=os.path.dirname(os.path.abspath(__file__))
def handle(self):
print(self.request)
while True:
data=self.request.recv(4)
data_len=struct.unpack('i',data)[0]
head_json=self.request.recv(data_len).decode(self.coding)
head_dic=json.loads(head_json)
# print(head_dic)
cmd=head_dic['cmd']
if hasattr(self,cmd):
func=getattr(self,cmd)
func(head_dic)
def put(self,args):
file_path = os.path.normpath(os.path.join(
self.BASE_DIR,
self.server_dir,
args['filename']
))
filesize = args['filesize']
recv_size = 0
print('----->', file_path)
with open(file_path, 'wb') as f:
while recv_size < filesize:
recv_data = self.request.recv(self.max_packet_size)
f.write(recv_data)
recv_size += len(recv_data)
print('recvsize:%s filesize:%s' % (recv_size, filesize))
ftpserver=socketserver.ThreadingTCPServer(('127.0.0.1',8080),FtpServer)
ftpserver.serve_forever()
客户端:
import socket
import struct
import json
import os
class MYTCPClient:
address_family = socket.AF_INET
socket_type = socket.SOCK_STREAM
allow_reuse_address = False
max_packet_size = 8192
coding='utf-8'
request_queue_size = 5
def __init__(self, server_address, connect=True):
self.server_address=server_address
self.socket = socket.socket(self.address_family,
self.socket_type)
if connect:
try:
self.client_connect()
except:
self.client_close()
raise
def client_connect(self):
self.socket.connect(self.server_address)
def client_close(self):
self.socket.close()
def run(self):
while True:
inp=input(">>: ").strip()
if not inp:continue
l=inp.split()
cmd=l[0]
if hasattr(self,cmd):
func=getattr(self,cmd)
func(l)
def put(self,args):
cmd=args[0]
filename=args[1]
if not os.path.isfile(filename):
print('file:%s is not exists' %filename)
return
else:
filesize=os.path.getsize(filename)
head_dic={'cmd':cmd,'filename':os.path.basename(filename),'filesize':filesize}
print(head_dic)
head_json=json.dumps(head_dic)
head_json_bytes=bytes(head_json,encoding=self.coding)
head_struct=struct.pack('i',len(head_json_bytes))
self.socket.send(head_struct)
self.socket.send(head_json_bytes)
send_size=0
with open(filename,'rb') as f:
for line in f:
self.socket.send(line)
send_size+=len(line)
print(send_size)
else:
print('upload successful')
client=MYTCPClient(('127.0.0.1',8080))
client.run()
来源:https://www.cnblogs.com/vipchenwei/p/7205872.html
标签:Python,Socket,多线程,并发
0
投稿
猜你喜欢
Python在后台自动解压各种压缩文件的实现方法
2022-10-04 17:59:59
Python OpenCV之常用滤波器使用详解
2023-02-07 22:18:25
python迭代器常见用法实例分析
2023-07-12 02:40:54
python sys.argv[]用法实例详解
2023-10-15 17:21:55
pandas创建DataFrame的方式小结
2021-10-25 13:26:23
Python爬虫,获取,解析,存储详解
2023-12-21 15:03:23
Oracle中大批量删除数据的方法
2010-07-21 13:05:00
Django 实现admin后台显示图片缩略图的例子
2022-05-30 19:46:02
CSS的学习应该注意学习方法
2007-11-27 00:20:00
修改Vue打包后的默认文件名操作
2024-06-07 16:03:07
python设置代理和添加镜像源的方法
2022-12-03 10:26:39
优化SQL Server的内存占用之执行缓存
2012-04-13 11:45:06
python中numpy包使用教程之数组和相关操作详解
2022-10-26 19:18:40
SQL Server 2005数据库中表的递归查询
2009-01-08 16:08:00
Python免登录实现域名解析的示例详解
2022-12-17 21:26:50
Python入门学习之字符串与比较运算符
2023-10-14 22:09:40
Python使用遗传算法解决最大流问题
2023-02-19 10:49:57
ie7.0浏览器 兼容问题苦煞网站设计者
2007-08-08 17:11:00
Python numpy之线性代数与随机漫步
2021-12-04 05:20:01
对Python中range()函数和list的比较
2021-08-26 14:59:47