Python efficient socket communication
Question: i recently started making a pure skype resolver and after doing everything
fine i stuck on the socket communication.

## Let me explain

I'm using python to get the user's IP and then the script opens a socket
server and it sends the username to an other program written in .NET

Why is that? Well, the python skype API is not that powerfull so i'm using the
axSkype library in order to gather more info.

## The problem

The python socket sends the username as it should but i dont know the most
efficient way to get the info back. I was thinking opening a socket server in
the same script and wait for what the .NET program sends back.

I dont really kwon how to make this as fast as possible so i'm asking for your
help.

## The code

    
    
    class api:
      def GET(self, username):
        skypeapi.activateSkype(username)
        time.sleep(1) # because skype is ew
        buf = []
        print("==========================")
        print("Resolving user " + username)
        #This is where i'm starting the socket and sending data
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect(("127.0.0.1", 5756))
        s.sendall(username)
        s.close()
        #at this poaint i want to get data back from the .NET app
        for logfile in glob.glob('*.log'):
            buf += logparse.search(logfile, username)
        print("Done!")
        print("==========================")
        return json.dumps(buf)
    
    class index:
     def GET(self):
        return render.index()
    
    if __name__ == "__main__":
       app.run()
    


Answer: You can bind your socket to the connection. This way, your socket stream will
remain open and you will be able to send and receive information easily.
Integrate this with the `_thread` module and you will be able to handle
multiple streams. Here is some example code that binds a socket to a stream
and just sends back whatever the clients sends it(Although in your case you
could send whatever data is necessary)

    
    
    import socket
    from _thread import *
    
    #clientHandle function will just receive and send stuff back to a specific client.
    def clientHandle(stream):
        stream.send(str.encode("Enter some stuff: "))
        while True:
            #Here is where the program waits for a response. The 4000 is a buffer limit.
            data = stream.recv(4000)
            if not data:
               #If there is not data, exit the loop.
               break
            stream.senddall(str.encode(data + "\n"))
    
            #Creating socket.
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            host = "" #In this case the host is the localhost but you can put your host
            port = 80
            try:
                #Here the program tries to bind the socket to the stream.
                s.bind((host, port))
            except socket.error as e:
                print("There was an error: " + str(e))
    
            #Main program loop. Uses multithreading to handle multiple clients.
            while True:
                conn, addr = s.accept()
                print("Connected to: " + addr[0] + ": " + str(addr[1]))
                start_new_thread(clientHandle,(conn,))
    

Now in your case, you can integrate this into your `api` class(Is that where
you want to integrate it? Correct me if I'm wrong.). So now when you define
and bind your socket, use this code:

    
    
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((host, port))
    

Where, in your case, `host` is `127.0.0.1`, in other words, your localhost,
which can also be accessed by `socket.gethostbyname(socket.gethostname())`(but
that's a bit verbose), and then `port`, which for you is `5756`. Once you have
bounded your socket, you have to accept connections through the following
syntax:

    
    
    conn, addr = s.accept()
    

Which then you can pass `conn` and `addr` to whatever function or just use in
any other code.

Regardless of what you use it in, to receive data you can use `socket.recv()`
and pass it a buffer limit. (Remember to decode whatever you receive.) And of
course, you send data by using `socket.sendall()`.

If you combine this with the `_thread` module, as shown above, you can handle
multiple api requests, which could come handy in the future.

Hope this helps.

