I am working with sockets. I have written code for python server which will receive data from a c# client and will display it in the console. The data may be an image or a text. Now problem is that how to differentiate between image and text because text must be displayed in the console and image has to save on the disk. Following is the code:
import socket
import os
import io
import os.path
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
self.data=self.request.recv(1024).strip()
print ("{} wrote:".format(self.client_address[0]))
if os.path.isfile("image.png"):
os.remove("image.png")
file = open("image.png", "wb")
while True:
data = self.request.recv(1024)
if not data:
break
file.write(data)
print(str(list(data)))
print("Done.")
print (self.data)
self.request.sendall(self.data.upper())
if __name__ == "__main__":
HOST, PORT = socket.gethostname(), 11000
print ("IP: "+socket.gethostbyname('BlackZero-PC'))
print ("Host: "+socket.gethostname())
server=socketserver.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()