Sunday, December 6, 2015

Python - MultiThreading example using socket connect (Python2.x)

The following example created displays how to create multiple threads in python, a client and server. A server thread is created first to create a socket connection and waits for client to connect.  The client will start and attempt to connect with server.  When the second thread starts, the client will connect with the server and receive a message from the server.



main.py:
import server
import client
from threading import Thread
import threading



def main():
    try:
         
        #Create a new thread 
        threadA = Thread(target=server.connServer)    
        #Start thread 
        threadA.start() 
 
        #Wait was added to allow some time for threadA to start.
        threading._sleep(1)

        #Create a new thread 
        threadB = Thread(target=client.connClient)
        #Start thread 
        threadB.start()
    except:
        print("Error unable to start thread")

if __name__ == '__main__':
    main()


 

client.py:
import socket               #Import socket module
def connClient():
    #Create a socket object 
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)         
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
    # Get local machine name
    host = socket.gethostname() 
    # Reserve a port for your service.     
    port = 12345                
    s.connect((host, port))
    print s.recv(1024)
    # Close the socket when done
    s.close()                   
 
server.py:
import socket
import threading

def connServer():
    #Create a socket object  
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    #Get local machine name
    host = socket.gethostname()
    #Reserve a port for your service. 
    port = 12345
    #Create a socket object                  
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
    s.bind((host,port))

    try:
        # Now wait for client connection
        s.listen(5)
        # Establish connection with client
        c, addr = s.accept()
        print ('Got connection from', addr)
        c.send('Thank You for connecting')
         
   # Close the connection
        c.close()
   # Close the socket when done
        s.close()
    except:
        s.shutdown(1)

 
 
 



No comments:

Post a Comment