vinit parakh
vinit parakh

Reputation: 35

How to apply multithreading in python socket programming, I tried but not works?

In this code, When I tried without applying multithreading on python socket, it works perfectly fine. But after using multithreading for concurrency, the first while loop works fine, but in the 2nd while loop, it takes it as 2nd thread, which doesn't complete the procedure of sending passkey to android. Here, I dont want 2nd loop as 2nd thread. How will I do that ? Any help will be appreciated!

import mysql.connector as mysql 
import socket
import sys 
import json
import threading


mydb1=mysql.connect(
        user = 'rajat',
        passwd = 'rajat',
        host = 'localhost',
        database = 'master_database'
        )

class ClientThread(threading.Thread):
    def __init__(self,clientAddress,clientsocket):
        threading.Thread.__init__(self)
        self.csocket = clientsocket
        self.addr = clientAddress
        print ("New connection added: ", clientAddress)

    def run(self):
        print ("Connection from : ", self.addr)
        #self.csocket.send(bytes("Hi, This is from Server..",'utf-8'))
        msg = ''

        while True:
            #csocket, clientAddress = s.accept()
            #print ('Connect with ' + addr[0] + ':' + str(addr[1]))
            df7 = self.csocket.recv(1024)#Receiving the data in df7
            df8 = json.loads(df7)
            df2 = list(df8.values())


            mycursor4=mydb1.cursor()
            mycursor4.execute("SELECT bar_code_no FROM form_simpleform")
            obj1 = mycursor4.fetchone()
            qr_obj=print(obj1[0])


            mycursor3 = mydb1.cursor()
            mycursor3.execute("SELECT bar_code_no FROM bar_code")
            obj2 = mycursor3.fetchone()
            bar_obj=print(obj2[0])


            if qr_obj == bar_obj:
                print("This bar code has a existence in the database.")
            else:
                print("This bar code does not exist.")


            mycursor1=mydb1.cursor()
            mycursor1.execute("SELECT * FROM form_simpleform WHERE id=1")
            df3=mycursor1.fetchone()


            if df2 == (list(df3)):
                print('Data of QR Code also Exists')

                mycursor2 = mydb1.cursor()
                mycursor2.execute("SELECT * FROM android_display_data")
                df4 = mycursor2.fetchone()

                self.csocket.send(str(df4).encode('utf-8'))
                print("Data(Name, Email_id, Phone_No) is sent to the client ")
                self.csocket.close()

                message=[]

                while True:
                    clientsock, clientAddress = s.accept()
                    message = self.csocket.recv(1024).decode('ISO-8859-1')

                    print("Received new message from client")
                    op=((message).split(","))
                    print(op)
                    d = dict(s.split(':') for s in op)
                    yo = print(list(d.values()))


                    mycursor5 = mydb1.cursor()
                    sql2 = ("INSERT INTO imeiserial (IMEI, SimSerialNumber) VALUES (%s, %s)")
                    result = mycursor5.execute(yo, sql2)
                    print("Data inserted into bar_code Database")


                    pass_key = '90i5n4r16191'
                    self.csocket.send(str(pass_key).encode('utf-8'))
                    print(" Passkey send to Android ")

                    break
            else:
                print('Invalid Data')
            break
        print('Connection Closed!!')


        #s.close()
LOCALHOST = "192.168.0.121"
PORT = 8011
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((LOCALHOST, PORT))
print("Server started")
print("Waiting for client request..")
while True:
    s.listen(5)
    clientsock, clientAddress = s.accept()
    newthread = ClientThread(clientAddress, clientsock)
    newthread.start()

The Output which I am getting-

    Server started
Waiting for client request..
Connection from :  ('192.168.0.108', 42762)
456456
456456
This bar code has a existence in the database.
Data of QR Code also Exists
Data(Name, Email_id, Phone_No) is sent to the client
Connection from :  ('192.168.0.108', 42764)
Exception in thread Thread-2:
Traceback (most recent call last):
  File "C:\Users\Pallavai\Nox_share\AnacondaNEW\lib\threading.py", line 917, in _bootstrap_inner
    self.run()
  File "server-side2.py", line 34, in run
    df8 = json.loads(df7)

Upvotes: 1

Views: 53

Answers (1)

Orkun Kocyigit
Orkun Kocyigit

Reputation: 1147

When you run ClientThread class you are trying to call for clientAdress variable that is never defined in your current scope.

def run(self):
    print ("Connection from : ", clientAddress)

Henceforth clientAdress throws an error. To way to solve this is, assign clientAddress during init method then call it via self.clientAddress.

class ClientThread(threading.Thread):
    def __init__(self,clientAddress,clientsocket):
        threading.Thread.__init__(self)
        self.csocket = clientsocket
        self.addr = clientAddress
        print ("New connection added: ", clientAddress)


def run(self):
    print ("Connection from : ", self.addr)

Upvotes: 1

Related Questions