Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

python network client server communication problem

am trying to a file in this chase an image between a server and a client but the image comes out on the client side broken in some way and it can't be viewed

note: i didn't understand how to add code in any other way so am adding it like this if there is a batter way to add code for the viewing of others please late me know :)

sever side code ------------------------------------------------

import socket
from PIL import ImageGrab
import os

s_server = socket.socket()
s_server.bind(('0.0.0.0',8820))

s_server.listen(2)

c_sock, c_addr = s_server.accept()
print c_sock,c_addr


path = r'C:\Cyber\server\screenshot.jpeg'
im = ImageGrab.grab()
im.save(path)

c_req = c_sock.recv(1024)
if c_req == 'image':
    with open(path,'rb') as f:
        data = f.read()
        length = len(data)
        c_sock.sendall(data)

else:
     with open(path,'rb') as f:
        data = f.read()
        length = len(data)
        c_sock.sendall(str(length))




s_server.close()
c_sock.close()

client side code--------------------------------------------------

import socket
import os

c_sock = socket.socket()
c_sock.connect(('127.0.0.1',8820))

path = r'C:\Cyber\client\screen.jpeg'

# c_sock.send('filezise')
# filesize = c_sock.recv(1024)


c_sock.send('image')
data = c_sock.recv(1024)
with open(path,'wb') as f:
    # print filesize
    while data :
        data = c_sock.recv(1024)
        f.write(data)

[MOD: added ```python markdown formatting -cf]