###简单的实例
__author__ = '12711'
#-*- coding:utf-8 -*-
#客户端
# import socket
# client=socket.socket()#声明socket类型,同时生成sockte链接对象
# client.connect(('localhost',6969))
#
# client.send(b'Hello World')#发数据
# data=client.recv(1024)#接受服务器返回
# print('recv',data)
#
# client.close()#关闭
#服务器端
import socket
server=socket.socket()
server.bind(('localhost',6969))#绑定要监听的端口
server.listen()#监听
print('开始等待')
conn,addr=server.accept()#等待电话打进来
print('电话来了')
data=conn.recv(1024)#接收消息
print('recv:',data)
conn.send(data.upper())
server.close()
进阶的服务器端
#改良版 可收多个消息
# import socket
# server=socket.socket()
# server.bind(('localhost',6969))
# server.listen()
# while True:
# conn,addr=server.accept()
# while True:
#
# data=conn.recv(102400)
# print("收到的消息:",data.decode())
# data2=input('你要发送的消息')
# conn.send(data2.encode("utf-8"))
# server.close()
#加强版可以收发大数据
# import socket
# import os
# server=socket.socket()
# server.bind(('localhost',6969))
# server.listen()
# while True:
# conn,addr=server.accept()
# while True:
#
# data=str(conn.recv(1024).decode())
# print('收到的命令:',data)
#
# cmd=os.popen(data).read().encode("utf-8")
# cmd_seif=str(len(cmd))
# conn.send(cmd_seif.encode("utf-8"))
# conn.send(cmd)
#
#
#
#
# server.close()
#收发文件md5验证
import socket
import hashlib
server=socket.socket()
import os
server.bind(('localhost',6969))
server.listen()
while True:
coon,addr=server.accept()
while True:
data=coon.recv(1024)
cmd,filename=data.decode().split()
print(filename)
if os.path.isfile(filename):
f=open(filename,"rb")
m=hashlib.md5()
flie_size=os.stat(filename).st_size
coon.send(str(flie_size).encode("utf-8"))
coon.recv(1024)
for line in f:
m.update(line)
coon.send(line)
print("md5",m.hexdigest())
f.close()
coon.send(m.hexdigest().encode("utf-8"))
print("发送完毕")
server.close()
进阶的客户端
#可以发送多条消息
# import socket
# client=socket.socket()
# client.connect(('localhost',6969))
# while True:
# data1=input('亲输入:').strip()
# if not data1 :
# print("消息不能为空")
# continue
#
# client.send(data1.encode('utf-8'))
# data=client.recv(102400)
# print("服务器端:",data.decode())
#
# client.close()
#可以收发大数据
# import socket
# client=socket.socket()
# client.connect(('localhost',6969))
# while True:
# data=input('请输入:')
# if not data:
# print("输入的不能为空")
# continue
# client.send(data.encode("utf-8"))
# data1=client.recv(1024)
# print("收到的消息长度",data1.decode())
# print(type(data1))
# add=0
# data2=b''
# while add<int(data1):
# data3=client.recv(1024)
# add+=len(data3)
# data2+=data3
# print(data2.decode())
# print("接受的长度为:",add)
#
#
#
# client.close()
#可以接受文件并且md5验证
import hashlib
import socket
import os
client=socket.socket()
client.connect(('localhost',6969))
while True:
cmd=input("请输入指令和文件名")
if not cmd:
print("输入的不能为空")
continue
if cmd.startswith("get"):
client.send(cmd.encode())
file_size=client.recv(1024)
print("File size:",file_size)
client.send(b"ready to ercv file")
recv_file_size=0
filename=cmd.split()[1]
f=open(filename+"new","wb")
#m = hashlib.md5()
m=hashlib.md5()
while recv_file_size<int(file_size.decode()):
if int(file_size.decode())-recv_file_size>1024:
size=1024
else:
size=int(file_size.decode())-recv_file_size
print("最后一次的大小:",size)
data=client.recv(size)
recv_file_size+=len(data)
m.update(data)
f.write(data)
new_flie_md5=m.hexdigest()
print("文件接受完毕:",recv_file_size)
f.close()
server_file_md5=client.recv(1024)
print("server file md5:",server_file_md5)
print("new file md5:",new_flie_md5)
client.close()
Tcp实例代码只写了用户上传文件
#服务器端 可以同时与多个用户交流
__author__ = '12711'
#-*- coding:utf-8 -*-
import socketserver
import json,os
class MyTCPHandler(socketserver.BaseRequestHandler):
def put(self,*args):
cmd_dic=args[0]
file_name=cmd_dic["filename"]
file_size=cmd_dic["size"]
if os.path.isfile(file_name):
f=open(file_name+"new","wb")
else:
f=open(file_name,"wb")
self.request.send(b"keyifasong")
rvev_size=0
while rvev_size<file_size:
data=self.request.recv(1024)
f.write(data)
rvev_size+=len(data)
print("%s文件传输完毕"%(file_name))
def handle(self):
while True:
try:
self.data=self.request.recv(1024)
print("{} wrote:".format(self.client_address[0]))
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(e)
break
if __name__=="__main__" :
HOST,PORT="localhost", 6969
server=socketserver.ThreadingTCPServer((HOST,PORT),MyTCPHandler)
server.serve_forever()
#客户端
__author__ = '12711'
#-*- coding:utf-8 -*-
import socket
import os,json
class TcpClient(object):
def __init__(self):
self.client=socket.socket()
def help(self):
msg='''
ls
pwd
cd ../..
get filename
put filename
'''
print(msg)
def connect(self,ip,port):
self.client.connect((ip,port))
def interactive(self):
while True:
cmd=input("请输入:")
if not cmd:
print("不能让为空")
continue
cmd_str=cmd.split()[0]
if hasattr(self,"cmd_%s"%cmd_str):
func=getattr(self,"cmd_%s"%cmd_str)
func(cmd)
else:
help()
def cmd_put(self,*args):
cmd_split = args[0].split()
if len(cmd_split)>1:
filename=cmd_split[1]
if os.path.isfile(filename):
file_size=os.stat(filename).st_size
msg_dic={
"action": "put",
"filename":filename,
"size": file_size,
"overridden":True
}
self.client.send(json.dumps(msg_dic).encode("utf-8"))
self.client.recv(1024)
f=open(filename,"rb")
for line in f:
self.client.send(line)
print(filename,"发送完毕")
f.close()
else:
print(filename,"不是文件")
ftp=TcpClient()
ftp.connect('localhost',6969)
ftp.interactive()