Wednesday, November 4, 2020

Socket programming with python(sending text messages and image files)

          Recently I was working with socket programming and I was amazed to learn how we can communicate between 2 machines placed remotely. With sockets, not only communicating we can send/receive any kind of data including images. So I thought of sharing this knowledge with you all. 


          We will directly go to the implementation as there are many descriptions online about the socket programming. Today I will share two implementation, first one is sending text messages between sockets and second one is sending image from server to client machine via sockets. So Let’s get started:

    1.Sending text messages between machines via sockets:
    Server Side: In the server we have a bind() method which binds it to a specific ip(or local if connected via LAN) and port so that it can listen to incoming requests on that ip and port. The server also has a listen() method which puts the server into listen mode. This allows the server to listen to incoming connections. And last a server has an accept() and close(). Please see the below code for example. You can download the code from github
           Client side: The client code will connect with the server machine with the specified ip/local and print the received massage
You need to run the server code first, once you run it, it will print “Server started listening” , then run the client code which will print “Hey! Welcome” . Here is the output from the terminals

 
2.Sending images from server machine to client via sockets:
    We will use opencv to read image data at the server and then pack the data with pickle to send it to the client machine. In the client machine we will unpack the data with pickle and then display it.

    Server code:
            Server code would be similar with the above mentioned code, except the part of reading the image with opencv and dumping it with pickle.
    Then with a while loop we will send the data as long as it takes
        After the whole data is send we will shutdown and close connection
    Client Code:
        In the client side we will get the data size first, then retrieve the data
   
Then we will convert the data for visualization and show it with opencv

    Note:
While packing and unpacking data for sockets be careful about the format. For example if it is linux -> linux , then in the ‘struct.pack’ function we need to specify it as 'L', whereas communicating with R-pi or windows it should be '=L' .

         You can download the whole code from github. Do share your comments and feedback below. Stay inside, stay safe and keep learning cheers.