开发者

How to read a binary file?

I'm trying to send a file between a client and a server in my home network. I just want to test with a simple file, client.txt.

The client program should read X bytes and send it over the tcp socket I've created, but I cant wrap my head around how to do the sending part:

f = open("clie开发者_开发问答nt.txt", "rb")
while 1:
// should read X bytes and send to the socket

I think I need to check if the data I want to send is valid, if a file for instance is smaller then the amount (1024 for instance) I'm sending in each batch.... or does it not work that way?


Since you mentioned you have problems setting up the server part, I'll rip this out from Python documentation and edit it slightly:

import socket

HOST = ''
PORT = 50007

s = socket.socket()
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()

f = open("client.txt", "rb")
while 1:
    data = f.read(1024)
    if not data: break
    conn.send(data)
conn.close()

The relevant document can be found here


read() takes an optional parameter that specifies the number of bytes to read in.

Documentation

To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string. size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size bytes are read and returned. If the end of the file has been reached, f.read() will return an empty string ("").

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜