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使用的更多相关文章

  1. python3中socket套接字的编码问题解决

    一.TCP 1.tcp服务器创建 #创建服务器 from socket import * from time import ctime #导入ctime HOST = '' #任意主机 PORT = ...

  2. 详解:Python2中的urllib、urllib2与Python3中的urllib以及第三方模块requests

    在python2中,urllib和urllib2都是接受URL请求的相关模块,但是提供了不同的功能.两个最显著的不同如下: 1.urllib2可以接受一个Request类的实例来设置URL请求的hea ...

  3. 常见的爬虫分析库(1)-Python3中Urllib库基本使用

    原文来自:https://www.cnblogs.com/0bug/p/8893677.html 什么是Urllib? Python内置的HTTP请求库 urllib.request          ...

  4. Python3中Urllib库基本使用

    什么是Urllib? Python内置的HTTP请求库 urllib.request          请求模块 urllib.error              异常处理模块 urllib.par ...

  5. python3给socket模块设置代理

    最近需要在公司学习socket编程,但是不能直接连接外网,需要设置一个代理才能正常访问.报错示例: import socket def blocking(wd): sock = socket.sock ...

  6. Python3中的字符串函数学习总结

    这篇文章主要介绍了Python3中的字符串函数学习总结,本文讲解了格式化类方法.查找 & 替换类方法.拆分 & 组合类方法等内容,需要的朋友可以参考下. Sequence Types ...

  7. Python3中使用PyMySQL连接Mysql

    Python3中使用PyMySQL连接Mysql 在Python2中连接Mysql数据库用的是MySQLdb,在Python3中连接Mysql数据库用的是PyMySQL,因为MySQLdb不支持Pyt ...

  8. python3 中mlpy模块安装 出现 failed with error code 1的决绝办法(其他模块也可用本方法)

    在python3 中安装其它模块时经常出现 failed with error code 1等状况,使的安装无法进行.而解决这个问题又非常麻烦. 接下来以mlpy为例,介绍一种解决此类安装问题的办法. ...

  9. python3中返回字典的键

    我在看<父与子的编程之旅>的时候,有段代码是随机画100个矩形,矩形的大小,线条的粗细,颜色都是随机的,代码如下, import pygame,sys,random from pygame ...

随机推荐

  1. SpringCloud基础教程学习记录

    这个学习记录是学习自翟永超前辈的SpringCloud的基础教程. 自己写这个教程的目的主要是在于,想要更凝练总结一些其中的一些实用点,顺便做个汇总,这样自己在复习查看的时候更加方便,也能顺着自己的思 ...

  2. centos6.5 安装gcc 4.9.0

    wget http://gcc.skazkaforyou.com/releases/gcc-4.9.0/gcc-4.9.0.tar.gz  // 下载源码 tar -zxvf gcc-4.9.0 cd ...

  3. @property_@synthesize 配套使用

    @property 类默认实现变量的get set方法 @synthesize 是指定那个变量的 get和set方法 eg: .h文件中定义 类Student中含有两个 int age,和int _a ...

  4. 【render】partial及其局部变量

    原文:http://www.cnblogs.com/lwm-1988/archive/2011/09/13/2175041.html 1. partial 1.1 把partial作为view的一部分 ...

  5. web基础 (二) html标签

    一.html是什么? 超文本标记语言(Hypertext Markup Language,HTML)通过标签语言来标记要显示的网页中的各个部分.一套规则,浏览器认识的规则 浏览器按顺序渲染网页文件,然 ...

  6. SUSE 设置IP地址、网关、DNS

    说明: ip:172.18.4.107 子网掩码:255.255.255.0 网关:172.18.4.254 dns:172.18.0.6 1.设置ip地址 vi /etc/sysconfig/net ...

  7. 无人零售的黑科技:RFID技术

    无人零售的黑科技:RFID技术说起最近的热门话题,“无人零售商店”当属其一.自去年底,亚马逊推出第一家无人实体超市Amazon Go,到阿里.京东.大润发等各大企业纷纷加入,无人商店被推上了风口浪尖. ...

  8. 服务器启动时Webapp的web.xml中配置的加载顺序

    一 1.启动一个WEB项目的时候,WEB容器会去读取它的配置文件web.xml,读取<listener>和<context-param>两个结点. 2.紧急着,容创建一个Ser ...

  9. ORA -04098 触发器无效且未通过重新验证

    转自:https://blog.csdn.net/m15188153014/article/details/53080187 ORACLE 菜鸟,犯了一个低级错误,用PowerDesigner的SQL ...

  10. Tomcat 不能正常启动

    启动过程提示: Stopping ProtocolHandler ["http-bio-8080"] the JRE_HOME environment variable is no ...