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 ...
随机推荐
- 2、配置Selenium RC
1.相关Jar包:链接: https://pan.baidu.com/s/1YLp-_5t7heyzPg550BWTGg 密码: w7ne 2.启动Selenium的方法 (1)cmd命令进入sele ...
- 聊聊WPF中的Dispatcher
DispatcherObject,Dispatcher,Thread之间的关系 我们都知道WPF中的控件类都是从System.Windows.Threading.DispatcherObject继承而 ...
- bootstrap-table 父子表入门篇
官方文档:http://bootstrap-table.wenzhixin.net.cn/zh-cn/documentation/#多语言 一.引入js.css <!-- 引入bootstrap ...
- unix下网络编程之I/O复用(四)
首先需要了解的是select函数: select函数 #include<sys/select.h> #include<sys/time.h> int select (int m ...
- jQuery 实现最简单的form表单提交 Loding 功能
<html> <head><title></title></head> <body> <form name="e ...
- DCloud-wap2app:杂项
ylbtech-DCloud-wap2app:杂项 1.返回顶部 2.返回顶部 3.返回顶部 4.返回顶部 5.返回顶部 6.返回顶部 7.返回顶部 8.返回顶部 ...
- spring事务 异常回滚
spring事务回滚 可抛出自定义继承自RuntimeException
- 解决django不能以本机ip地址访问
在使用django框架来架设网站时,我们测试一般是通过django的开发服务器来完成,但是我们可以看到生成的地址是127.0.0.1:8000这样的话,我们在外网就无法访问了. 解决办法是通过传入第三 ...
- 转载 : JSP取得绝对路径
转自:https://www.aliyun.com/jiaocheng/770177.html 转自:http://www.cnblogs.com/xdp-gacl/p/3707243.html 在J ...
- 最全 C 语言常用算法详解-排序-队列-堆栈-链表-递归-树 (面试有用)
具体 源代码 案例查看github,持续更新中............ github地址:https://github.com/Master-fd/C-Algorithm 1. 二分法查找 2. 冒泡 ...