Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

newbie: write content in a file (server-side)

19 views
Skip to first unread message

Thomas Kaufmann

unread,
Jul 29, 2012, 10:16:01 AM7/29/12
to
Hi,

I send from a client file content to my server (as bytes). So far so good.
The server receives this content complete. Ok. Then I want to write this content to a new file. It works too. But in the new file are only the first part of the whole content.

What's the problem.

o-o

Thomas

Here's my server code:



import socketserver

class MyTCPServer(socketserver.BaseRequestHandler):

def handle(self):

s = ''
li = []
addr = self.client_address[0]
print("[{}] Connected! ".format(addr))
while True:

bytes = self.request.recv(4096)
if bytes:
s = bytes.decode("utf8")
print(s)
li = s.split("~")
with open(li[0], 'w') as fp:
fp.write(li[1])

#... main ......................................................

if __name__ == "__main__":

server = socketserver.ThreadingTCPServer(("", 12345), MyTCPServer)
server.serve_forever()

Peter Otten

unread,
Jul 29, 2012, 11:16:11 AM7/29/12
to pytho...@python.org
Thomas Kaufmann wrote:

> I send from a client file content to my server (as bytes). So far so good.
> The server receives this content complete. Ok. Then I want to write this
> content to a new file. It works too. But in the new file are only the
> first part of the whole content.
>
> What's the problem.

> Here's my server code:

> while True:
> bytes = self.request.recv(4096)
> if bytes:
> s = bytes.decode("utf8")
> print(s)
> li = s.split("~")
> with open(li[0], 'w') as fp:
> fp.write(li[1])

- Do you ever want to leave the loop?

- You calculate a new filename on every iteration of the while loop --
probably not what you intended to do.

- The "w" argument tells Python to overwrite the file if it exists. You
either need to keep the file open (move the with... out of the loop) or open
it with "a".

- You may not receive the complete file name on the first iteration of the
while loop.

- The bytes buffer can contain incomplete characters, e. g.:

>>> data = b"\xc3\xa4"
>>> data.decode("utf-8")
'ä'
>>> data[:1].decode("utf-8")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf8' codec can't decode byte 0xc3 in position 0:
unexpected end of data


Thomas Kaufmann

unread,
Jul 30, 2012, 5:50:12 AM7/30/12
to comp.lan...@googlegroups.com, pytho...@python.org
Thanks Peter. It helps;-).

Thomas Kaufmann

unread,
Jul 30, 2012, 5:51:18 AM7/30/12
to
Thanks a lot. It helps.

Thomas Kaufmann

unread,
Jul 30, 2012, 5:50:12 AM7/30/12
to pytho...@python.org
Am Sonntag, 29. Juli 2012 17:16:11 UTC+2 schrieb Peter Otten:
0 new messages