Click here to Skip to main content
14,331,975 members
Rate this:
Please Sign up or sign in to 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):
        print ("{} wrote:".format(self.client_address[0]))
        if os.path.isfile("image.png"):

        file = open("image.png", "wb")
        while True:
            data = self.request.recv(1024)
            if not data:

        print (

if __name__ == "__main__":
    HOST, PORT = socket.gethostname(), 11000
    print ("IP: "+socket.gethostbyname('BlackZero-PC'))
    print ("Host: "+socket.gethostname())

    server=socketserver.TCPServer((HOST, PORT), MyTCPHandler)
Updated 23-Aug-19 3:36am

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

You need to add some extra data to each message that identifies what is being sent - text or image.
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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100