Python socket for file upload and download

Source: Internet
Author: User

!/bin/python

#coding: Utf-8
Import Socketserver
Import OS
Import datetime
Import MySQLdb
Class MySQL:
DefInit(self):
Self.connect = MySQLdb.connect (
Host = ' 192.168.221.203 ',
user = ' Hall ',
passwd = ' 520157 ',
Port = 3306,
db = ' Info ',
charset = ' UTF8 '
)
def mysql_create_table_info (self):
cursor = Self.connect.cursor ()
sql = "" "CREATE table if not EXISTS info (
Action Char (20),
Actin_time varchar (40),
File_size varchar (20),
file_name varchar (40),
Operation_user Char (20)
)"""
Cursor.execute (SQL)
Cursor.close ()
Self.connect.commit ()
Self.connect.close ()
def mysql_create_table_user (self):
cursor = Self.connect.cursor ()
Sql_user = "" "CREATE table if not exists user (
User varchar (20),
passwd varchar (40)
)"""
Cursor.execute (Sql_user)
data = "" INSERT into user values (
"Hall",
"Hall"),
("Hexulin",
"Hexulin") "" "
Cursor.execute (data)
Cursor.close ()
Self.connect.commit ()
Self.connect.close ()

Class Server (Socketserver.baserequesthandler,mysql):
def handle (self):
Self.request
Self.client_address
Print "%s:%s is connecting ..."%self.client_address
recv = SELF.REQUEST.RECV (1024)
Print recv
Self.request.send ("Connection already established")
recv = SELF.REQUEST.RECV (1024)
Print recv
Operation = Recv.split (': ') [1]
if operation = = "Put":
Self.file_name,self.file_size = Self.request.recv (1024x768). Split (' | ')
Self.request.send ("Everything is ready")
Recv_size = 0
Time_put = Datetime.datetime.now ()
File_path = ['/root/', Self.file_name]
File_path = ". Join (File_path)
f = open (File_path, ' WB ')
While recv_size! = Int (self.file_size):
if int (self.file_size)-recv_size > 1024:
Rdata = SELF.REQUEST.RECV (1024)
Recv_size + = Len (rdata)
Else
Rdata = self.request.recv (int (self.file_size)-recv_size)
recv_size = Int (self.file_size)
F.write (Rdata)
F.close ()
Print "File has been saved ...."
Connect = MySQLdb.connect (
Host = ' 192.168.221.203 ',
user = ' Hall ',
passwd = ' 520157 ',
Port = 3306,
db = ' Info ',
charset = ' UTF8 '
)
Value = [Operation,time_put,self.file_size,self.file_name, "Hall"]

        cursor = connect.cursor () data = "" "INSERT into info values (%s,                    %s,%s,%s,%s) "" " Cursor.execute (Data,value) cursor.close () Connect.commit () c                Onnect.close () Else:file_path = Self.request.recv (1024x768) file_name = Os.path.basename (File_path)                File_size = Os.stat (file_path). St_size self.request.send (file_name + ' | ' + str (file_size)) recv = SELF.REQUEST.RECV (1024x768) print recv send_size = 0 Time_get = Date Time.datetime.now () F = open (File_path, ' RB ') while True:file_data = F.read (1024x768) if not file_data:break self.req    Uest.send (File_data)            F.close () print "file has been transferred ..." Connect = MySQLdb.connect (host = ' 192.168.221.203 ')                , user = ' Hall ', passwd = ' 520157 ', port = 3306, db = ' info ', charset = ' UTF8 ') value = [Operation,time_get,file_size,file_name, "Hall"] Cur                            Sor = connect.cursor () data = "" "INSERT into info values (%s, %s,%s,%s,%s) "" "Cursor . Execute (Data,value) cursor.close () Connect.commit () Connect.clos E ()

Class Insert_mysql:
def mysql_info (self):
Connect = MySQLdb.connect (
Host = ' 192.168.221.203 ',
user = ' Hall ',
passwd = ' 520157 ',
Port = 3306,
db = ' Info ',
charset = ' UTF8 '
)

            cursor = connect.cursor()            data = """insert into info values(                   operation,                   time),                   self.file_size,                   self.file_name)"""            cursor.execute(data)            cursor.close()            connect.commit()            connect.close()
If name= = ' Main‘:
Server = Socketserver.threadingtcpserver ((' 192.168.221.203 ', 8888), server)
Server.serve_forever ()

Client
#!/bin/python
#coding: Utf-8
Import socket
Import OS

Sock = Socket.socket (socket.af_inet,socket. SOCK_STREAM)
Sock.connect (' 192.168.221.203 ', 8888)
Sock.send ("I want to connect you to file transfer ...")
recv = SOCK.RECV (1024)
Print recv
Operation = Raw_input ("Please input your choice usage:put or get:")
Sock.send ("I'm going to do this:%s"%operation)
if operation = = "Put":
File_path = raw_input ("Please input your Input_file_path:")
file_name = Os.path.basename (File_path)
File_size = Os.stat (file_path). st_size
Print File_size
Sock.send (file_name + ' | ' + str (file_size))
Print SOCK.RECV (1024)
f = open (File_path, ' RB ')
While True:
File_data = F.read (1024)
If not file_data:
Break
Sock.send (File_data)
F.close ()
Print "Upload file complete ..."
Else
File_path = raw_input ("Please input your Get_file_path:")
Sock.send (File_path)
File_name,file_size = Sock.recv (1024x768). Split (' | ')
Get_file_path = ['/root/', file_name]
Get_file_path = ". Join (Get_file_path)
Sock.send ("Can start sending, ready")
Recv_size = 0
f = open (Get_file_path, ' WB ')
While not int (file_size) = = Recv_size:
if int (int (file_size)-recv_size) > 1024:
Rdata = SOCK.RECV (1024)
Recv_size + = Len (rdata)
Else
Rdata = sock.recv (int (file_size)-recv_size)
recv_size = Int (file_size)
F.write (Rdata)
F.close ()
print "File Download complete ..."
Sock.close ()

Python socket for file upload and download

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.