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. JavaScript实现继承的几种重要范式

    一 原型链 1. 代码示例 function SuperType() { this.superProperty = true; } SuperType.prototype.getSuperValue ...

  2. 0. LeetCode 开篇

    LeetCode 开篇 很久以前(也许是几天之前,记忆力没那么好),听朋友说过,但是没怎么重视,最近发现自己基础打的不牢(会是会,但是说不出来,说不明白),故借此机会理一理知识点,并复习,巩固相关知识 ...

  3. postgresql 模式与用户,及跨库访问

    1 控制台命令\h:查看SQL命令的解释,比如\h select.\?:查看psql命令列表.\l:列出所有数据库.\c [database_name]:连接其他数据库.\d:列出当前数据库的所有表格 ...

  4. Git 之Windows环境下学习系列

    Git .SVN .TFS   相同点 不同点 Git     版本控制 优点: 分布式版本控制.无需联网就能版本提交 开源 缺点 入门学习难度高 SVN   优点: 集中式版本控制. 个人开源 缺点 ...

  5. 如何删除offline数据文件/表空间上的分区

    接上一篇"Oracle 10g RAC全库flashback " http://www.cnblogs.com/cqubityj/p/3265552.html 在打开数据库之前把2 ...

  6. maven 本地jar包依赖生成

    转载自:http://www.cnblogs.com/wuyouwulv/p/maven_configure_oracle_jdbc.html 由于Oracle授权问题,Maven不提供Oracle ...

  7. Java判断字符串是否包含数字

    public static boolean isContainNumber(String company) { Pattern p = Pattern.compile("[0-9]" ...

  8. apache server和tomcat集群配置三:水平集群下的tomcat集群配置

    在jsp文件中加入以下代码,用来测试是否共享session: SessionID: <%= session.getId() %> 之前尝试在linux中,但是因为模拟环境是虚拟机,虚拟机只 ...

  9. 【260】centos设置root密码

    怎么进Linux单用户模式 http://tieba.baidu.com/p/2216642385 http://jingyan.baidu.com/article/c1a3101ea68dafde6 ...

  10. 剑指offer 04_替换字符串中的空格

    #include <stdio.h> void ReplaceBlank(char string[],int length){ if(string == NULL || length == ...