Python3 中socket使用
1.动态导入模块
在当前目录下有lib和test目录,在test中要想使用lib中的aa的C类:
test中:
第一种方法:推荐
importlib.import_module('lib.aa')
obj = aa.c()
第二种方法:(python内部解释器用的)
lib = __import__("lib.aa")
obj = lib.aa.C()
2.断言:assert(预判,断定)
assert type("dsds") is str
print("yes")
如果断言错误,即"dsds"的类型不是str,则程序不能继续运行,会报错
若接下来的代码运行时非常重要,最好提前用断言
2.socket
Socket Families(地址簇)
socket.
AF_UNIX unix本机进程间通信
socket.
AF_INET IPV4
socket.
AF_INET6 IPV6
Socket Types 类型
socket.
SOCK_STREAM #for tcp
socket.
SOCK_DGRAM #for udp
实际例子:
服务器端:
import socket server = socket.socket()
server.bind(('localhost',6969))
server.listen(5) print('The server is ready')
while True:
conn,addr = server.accept()
print('The client is connected !!!')
while True:
data = conn.recv(1024)
print('recv:',data.decode())
conn.send(data.upper())
server.close
客户端:
import socket client = socket.socket()
client.connect(('localhost',6969)) while True:
msg = input('ibput>>').strip()
if len(msg) == 0:
continue
client.send(msg.encode('utf-8'))
data = client.recv(1024)
print('recv:',data.decode())
client.close()
实现回显数据:
服务器:
import socket,os server = socket.socket()
server.bind(('localhost',6969))
server.listen(5) print('The server is ready')
while True:
conn,addr = server.accept()
print('The client is connected !!!')
while True:
data = conn.recv(1024)
if not data:
break
# print('recv:',data.decode())
# conn.send(data.upper())
res = os.popen(data.decode()).read()
print('before send:',len(res))
if len(res) == 0:
res = 'cmd has no input'
conn.send(res.encode())
server.close
客户端:
import socket client = socket.socket()
client.connect(('localhost',6969)) while True:
msg = input('ibput>>').strip()
if len(msg) == 0:
continue
client.send(msg.encode('utf-8'))
data = client.recv(1024)
print('recv:',data.decode())
client.close()
可以回显全部的数据
利用了循环知道返回全部的数据长度
服务器端:
import socket,os
server = socket.socket()
server.bind(('localhost',6969))
server.listen(5)
print('The server is ready')
while True:
conn,addr = server.accept()
print('The client is connected !!!')
while True:
data = conn.recv(1024)
if not data:
break
res = os.popen(data.decode()).read()
print('before send:',len(res))
if len(res) == 0:
res = 'cmd has no input'
conn.send(str(len(res.encode())).encode())
conn.send(res.encode())
server.close
客户端:
import socket
client = socket.socket()
client.connect(('localhost',6969))
while True:
msg = input('ibput>>').strip()
if len(msg) == 0:
continue
client.send(msg.encode('utf-8'))
data_size = client.recv(1024)
print("The size is :",data_size.decode())
received_size = 0
received_data = b''
while received_size < int(data_size.decode()):
data = client.recv(1024)
received_size += len(data)
received_data += data
print(received_size)
else:
print('cmd res receive done...',received_size)
print(data.decode())
client.close()
实现FTP的下载功能:
服务器:
import socket,os,hashlib
server = socket.socket()
server.bind(('localhost',6969))
server.listen(5)
print('The server is ready')
while True:
conn,addr = server.accept()
print('The client is connected !!!')
while True:
data = conn.recv(1024)
if not data:
print('The client is gone...')
break
cmd,filename = data.decode().split()
print(filename)
if os.path.isfile(filename):
f = open(filename,'rb')
m = hashlib.md5()
file_size = os.stat(filename).st_size
conn.send(str(file_size).encode())
conn.recv(1024) #wait for ack
for line in f:
m.update(line)
conn.send(line)
print('file md5',m.hexdigest())
f.close()
print('send done')
server.close
客户端:
import socket
client = socket.socket()
client.connect(('localhost',6969))
while True:
cmd = input('ibput>>').strip()
if len(cmd) == 0:
continue
if cmd.startwith('get'):
client.send(cmd.encode('utf-8'))
server_reponse = client.recv(1024)
print('server response:',server_reponse)
client.send(b'ready to recv file')
file_total_size = int(server_reponse.decode())
received_size = 0
filename = cmd.split()[1]
f = open(filename + '.new','wb')
while received_size < file_total_size:
data = client.recv(1024)
received_size += len(data)
f.write(data)
print(file_total_size,received_size)
else:
print('file recv done',file_total_size,received_size)
f.close()
client.close()
实现FTP的交互:
服务器:
import socketserver,json,os class MyTCPHandler(socketserver.BaseRequestHandler):
def put(self,*args):
'''接收客户端文件'''
cmd_dic = args[0]
filename = cmd_dic['filename']
filesize = cmd_dic['size']
if os.path.isfile(filename):
f = open(filename+'.new','wb')
else:
f = open(filename,'wb') self.request.send(b'200 ok')
received_size = 0
while received_size < filesize:
data = self.request.recv(1024)
f.write(data)
received_size += len(data)
else:
print('file [%s] has uploaded'%filename)
f.close()
def get(self,*args):
cmd_dic = args[0]
filename = cmd_dic['filename']
filesize = os.stat(filename).st_size
if os.path.isfile(filename):
self.request.send(str(filesize).encode())
client_request = self.request.recv(1024)
f = open(filename,'rb')
for line in f:
self.request.send(line)
else:
f.close()
else:
print('file [%s] is not exist...'%filename) def handle(self):
while True:
try:
print('{} wrote:'.format(self.client_address[0]))
self.data = self.request.recv(1024).strip()
print(self.data)
cmd_dic = json.loads(self.data.decode())
action = cmd_dic['action']
if hasattr(self,action):
func = getattr(self,action)
func(cmd_dic)
except ConnectionResetError as e:
print('err',e)
break if __name__ == '__main__':
HOST,PORT = 'localhost',9999
server = socketserver.ThreadingTCPServer((HOST,PORT),MyTCPHandler)
server.serve_forever()
客户端:
import socket,os,json class FtpClient(object):
def __init__(self):
self.client = socket.socket()
def help(self):
msg = '''
ls
pwd
cd ../..
get filename
put filename
'''
print(msg)
def connect(self):
self.client.connect(('localhost',9999))
def interaction(self):
#self.authenticate()
while True:
cmd = input('>>').strip()
if len(cmd) == 0:continue
cmd_str = cmd.split()[0]
if hasattr(self,'cmd_%s'%cmd_str):
func = getattr(self,'cmd_%s'%cmd_str)
func(cmd)
else:
self.help()
def cmd_put(self,*args):
cmd_spilt = args[0].split()
if len(cmd_spilt) > 1:
filename = cmd_spilt[1]
if os.path.isfile(filename):
filesize = os.stat(filename).st_size
msg_dic = {
'action':'put',
'filename':filename,
'size':filesize,
'overridden':True
}
self.client.send(json.dumps(msg_dic).encode('utf-8'))
#防止粘包,等服务器确认
server_reponse = self.client.recv(1024)
f = open(filename,'rb')
for line in f:
self.client.send(line)
else:
print('file uupload success...')
f.close()
else:
print(filename,'is not exist')
def cmd_get(self,*args):
cmd_spilt = args[0].split()
if len(cmd_spilt) > 1:
filename = cmd_spilt[1]
msg_dic = {
'action': 'get',
'filename': filename
}
self.client.send(json.dumps(msg_dic).encode('utf-8'))
filesize = self.client.recv(1024)
self.client.send(b'200 ok')
if os.path.isfile(filename):
f = open(filename+'.new','wb')
else:
f = open(filename,'wb')
receive_size = 0
while int(filesize.decode()) > receive_size:
data = self.client.recv(1024)
f.write(data)
receive_size += len(data)
else:
print('file [%s] is downloaded...'%filename)
f.close() ftp = FtpClient()
ftp.connect()
ftp.interaction()
使用方法:例如get filename 或者 put filename
Python3 中socket使用的更多相关文章
- python3中socket套接字的编码问题解决
一.TCP 1.tcp服务器创建 #创建服务器 from socket import * from time import ctime #导入ctime HOST = '' #任意主机 PORT = ...
- 详解:Python2中的urllib、urllib2与Python3中的urllib以及第三方模块requests
在python2中,urllib和urllib2都是接受URL请求的相关模块,但是提供了不同的功能.两个最显著的不同如下: 1.urllib2可以接受一个Request类的实例来设置URL请求的hea ...
- 常见的爬虫分析库(1)-Python3中Urllib库基本使用
原文来自:https://www.cnblogs.com/0bug/p/8893677.html 什么是Urllib? Python内置的HTTP请求库 urllib.request ...
- Python3中Urllib库基本使用
什么是Urllib? Python内置的HTTP请求库 urllib.request 请求模块 urllib.error 异常处理模块 urllib.par ...
- python3给socket模块设置代理
最近需要在公司学习socket编程,但是不能直接连接外网,需要设置一个代理才能正常访问.报错示例: import socket def blocking(wd): sock = socket.sock ...
- Python3中的字符串函数学习总结
这篇文章主要介绍了Python3中的字符串函数学习总结,本文讲解了格式化类方法.查找 & 替换类方法.拆分 & 组合类方法等内容,需要的朋友可以参考下. Sequence Types ...
- Python3中使用PyMySQL连接Mysql
Python3中使用PyMySQL连接Mysql 在Python2中连接Mysql数据库用的是MySQLdb,在Python3中连接Mysql数据库用的是PyMySQL,因为MySQLdb不支持Pyt ...
- python3 中mlpy模块安装 出现 failed with error code 1的决绝办法(其他模块也可用本方法)
在python3 中安装其它模块时经常出现 failed with error code 1等状况,使的安装无法进行.而解决这个问题又非常麻烦. 接下来以mlpy为例,介绍一种解决此类安装问题的办法. ...
- python3中返回字典的键
我在看<父与子的编程之旅>的时候,有段代码是随机画100个矩形,矩形的大小,线条的粗细,颜色都是随机的,代码如下, import pygame,sys,random from pygame ...
随机推荐
- C# 保护进程不被结束(源代码)防任务管理器结束进程
C# 保护进程不被结束(源代码)防任务管理器结束进程 Posted on 2013-03-25 16:03 快乐家++ 阅读(3173) 评论(3) 编辑 收藏 闲来无事,英语又学的太痛苦.看到我妈妈 ...
- laravel 常用知识总结
看到一篇别人的文章感觉写的不错 就copy过来了 学习源头: https://www.cnblogs.com/yjf512/p/3830750.html aravel是个很强大的PHP框架,它剔除了开 ...
- java添加背景图片
总结:我们通常实现添加背景图片很容易,但是再添加按钮组件就会覆盖图片.原因是: 有先后啊.setlayout();与布局有很大关系 请调试代码的时候,仔细揣摩.我晕了 还可以添加文本框,密码框 fra ...
- 并集(union和union all的区别)、交集、差集、全连接
一.并集 Union因为要进行重复值扫描,所以效率低.如果合并没有刻意要删除重复行,那么就使用Union All 两个要联合的SQL语句 字段个数必须一样,而且字段类型要“相容”(一致): 如果我们需 ...
- L2-022. 重排链表
L2-022. 重排链表 时间限制 500 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 作者 陈越 给定一个单链表 L1→L2→...→Ln-1→Ln,请 ...
- Druid 0.2.25版本hive jdbc 不支持 conn.getHoldability() 兼容处理问题
背景: 用Druid做Oracle的连接池感觉还不错,近日新项目要用Hive,故而也想使用Duid来做Hive的连接池.试了试果真可以,也没报错.但是,过了一段时间,同样的代码却出问题了.离奇的是我同 ...
- 基于OpenCV的火焰检测(三)——HSI颜色判据
上文向大家介绍了如何用最简单的RGB判据来初步提取火焰区域,现在我要给大家分享的是一种更加直观的判据--HSI判据. 为什么说HSI判据是更加直观的判据呢?老规矩,先介绍一下HSI色彩模型: HSI颜 ...
- SQLServer数据库中开启CDC导致事务日志空间被占满的原因
SQLServer数据库中开启CDC导致事务日志空间被占满的原因 转载 2017-04-01 投稿:mrr 我要评论 这篇文章主要介绍了SQLServer数据库中开启CDC导致事务日志空间 ...
- 如何设置Win10文件资源管理器默认打开“这台电脑”
摘录自:http://www.ithome.com/html/win10/126066.htm
- SQl Server 函数篇 聚合函数
说一下数据库中的聚合函数 函数使用必须加小括号(), 5种聚合函数: 1.max最大值 select max(price) from car where code='c024' --取这一列中 ...