Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
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.

What I have tried:

Following is the python server 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()
Posted
Updated 23-Aug-19 3:36am

1 solution

You need to add some extra data to each message that identifies what is being sent - text or image.
 
Share this answer
 
Comments
Muhammad Afaq Riaz 23-Aug-19 11:16am    
Thanks, I have solved it like the same way as your answer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900