1

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 when 2nd while loop is not running until I will close the connection, doing so, it takes 2nd while loop as 2nd thread, which doesn't complete the procedure of sending passkey to android. Here, the problem is with 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



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 = ''

        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()

1 Answer 1

1

I solved this problem as my output will also come in the way I want.The basic idea of the solution is given below:-

import socket, threading

class ClientThread(threading.Thread):
    def __init__(self,clientAddress,clientsocket):
        threading.Thread.__init__(self)
        self.csocket = clientsocket
        print ("New connection added: ", clientAddress)
    def run(self):
        print ("Connection from : ", clientAddress)
        #self.csocket.send(bytes("Hi, This is from Server..",'utf-8'))

        while True:
            data = self.csocket.recv(1024).decode('utf-8')
            print(data)
            #print('its not data')

            self.csocket.send(b'This is from server side')
            break

        #self.csocket.close()


        #
LOCALHOST = "127.0.0.1"
PORT = 8080
server = socket.socket(socket.AT, F_INEsocket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((LOCALHOST, PORT))
print("Server started")
print("Waiting for client request..")
while True:
    server.listen(10)
    clientsock, clientAddress = server.accept()
    newthread = ClientThread(clientAddress, clientsock)
    newthread.start()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.