python传输mp3

IT小托 发布于 2015/06/13 23:39
阅读 225
收藏 1

使用python写了一个用来传输mp3的小程序,但是收到的mp3文件的大小与源文件不一样,不知道为什么会这样。

服务器端的代码:

#! -*- coding: utf-8 -*-


import socket
import sys
import base64
host = '127.0.0.1'
port = 3304
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((host,port))
s.listen(5)
music_list=[u'鸟之诗.mp3', u'富士山下.mp3']
while 1:
    print 'waiting for connecting:'
    clientsock,clientaddr = s.accept()
    print 'connect from', clientaddr
    while True:
        message = clientsock.recv(1024).decode('utf-8')
        if len(message) != 0:           
            if message in music_list:
                print 'The music is in the list'
                print './server_music/'+message
                with open('./server_music/'+message, 'rb') as f:
                    buf = base64.b64encode(f.read())
                    clientsock.send(buf)
                    print 'sending data to the client'
            else:
                clientsock.send('I am sorry, we do not have the music you request')
    clientsock.close()


客户端的代码:

#! -*- coding: utf-8 -*-


import socket
import base64
import time
import mp3play


host = '127.0.0.1'
port = 3304
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,port))


bytes_count = 0 # count how many bytes the client has received from the server


while True:
message=raw_input("<")
if not message:
continue
elif message.upper()=='QUIT':
break
else:
s.send(message.decode('gbk').encode('utf-8'))
time.sleep(1)
while True:
data=s.recv(1024)
if not data:
break
bytes_count+=len(data)
print 'receive %d bytes from server'%len(data)
if bytes_count == 4096:
filename = './client_music/' + message
mp3 = mp3play.load(filename)
mp3.play()
with open('./client_music/'+ message, 'a+') as f:
f.write(base64.b64decode(data))
s.close()


加载中
返回顶部
顶部