python套接字文件传输 [英] python socket file transfer

查看:135
本文介绍了python套接字文件传输的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过套接字写入传输文件或数据块.我感觉好像是在重新发明轮子,但是我对简单解决方案的搜索失败了(我发现的一切太简单或太复杂).该服务器将在运行python 2.5.4的手机上运行.预期的应用程序将是在电话和主机之间同步音乐文件.

I'm trying to write transfer files or chunks of data over a socket. I feel as if I'm reinventing the wheel, but my searches for a simple solution have failed (everything I find is either too simple or too complex). The server would run on a phone running python 2.5.4. The intended application would be to sync music files between the phone and a host computer.

这就是我所拥有的勇气,看来行之有效.我发送和接收确定"以中断流.

This is the guts of what I have, which appears to work. I send and receive 'ok' to break up streams.

从本质上讲,作为停止位来回发送确定"以破坏数据流是一种合理的技术吗?

Is sending 'ok' back and forth essentially as stop bits to break up streams of data a reasonable technique?

有标准的方法吗?

鉴于电话的内存和处理能力有限,在电话上运行任何类型的库服务器(ftp,http)都不是有用的解决方案.

Running any sort of library server (ftp, http) on the phone is not a useful solution given the limits of the phone's memory and processing power.

服务器:

import socket

c = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
c.bind(('', 1234))
c.listen(1)
s,a = c.accept()

while True:
    data = s.recv(1024)
    cmd = data[:data.find('\n')]

    if cmd == 'get':
        x, file_name, x = data.split('\n', 2)
        s.sendall('ok')
        with open(file_name, 'rb') as f:
            data = f.read()
        s.sendall('%16d' % len(data))
        s.sendall(data)
        s.recv(2)

    if cmd == 'end':
        s.close()
        c.close()
        break

客户端:

import socket

s = socket.socket()
s.connect(('192.168.1.2', 1234))

def get_file(s, file_name):
    cmd = 'get\n%s\n' % (file_name)
    s.sendall(cmd)
    r = s.recv(2)
    size = int(s.recv(16))
    recvd = ''
    while size > len(recvd):
        data = s.recv(1024)
        if not data: 
            break
        recvd += data
    s.sendall('ok')
    return recvd

print get_file(s, 'file1')
print get_file(s, 'file2')
s.sendall('end\n')

推荐答案

本质上是作为终止位来回发送"ok" 数据流是一种合理的技术吗?

Is sending 'ok' back and forth essentially as stop bits to break up streams of data a reasonable technique?

大多数协议都使用某些终止符或其他终止符.流行的替代方法是'\ r \ n','\ r \ n \ r \ n'或EOF(ctrl + d),但是这些都是任意选择的,只要您的客户满意,它的性能就不会比您的'ok'更好或更差和服务器知道如何处理.

Most protocols use some terminator or another. Popular alternatives are '\r\n', '\r\n\r\n' or EOF (ctrl+d), but these are just arbitrarily chosen and no worse or better than your 'ok', as long as your client and server know how to handle it.

这篇关于python套接字文件传输的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆