Как передать объекты из одного класса потока в другой класс потока в python - PullRequest
0 голосов
/ 22 апреля 2020

Я использую модуль сокета в python для создания двух клиентов и одного сервера. Клиент_1 должен отправить содержимое файла .txt на Клиент_2 через сервер. На сервере я использую модуль потока для поддержки нескольких клиентов.

Я создал три потока на моем сервере: -

1) Первый поток обрабатывает клиентские подключения 2) Второй поток получает содержимое файла .txt от Client_1 3) Третий поток отправляет это содержимое для Client_2

Проблема, с которой я сталкиваюсь при выполнении вышеупомянутого сервера Client_1 и Client_2. Содержимое файла .txt успешно отправлено с Client_1 на сервер. Но сервер не может отправить это содержимое в Client_2.

Это может быть потому, что третий поток не может получить содержимое, полученное во втором потоке (но я думаю, что это не так). Ниже я поделюсь всеми тремя кодами вместе с используемым мной .txt файлом.

код сервера

import socket
import threading

class ClientThread(threading.Thread):        ############ this thread manages the client connections ############
   def __init__(self,conn,Address):
       threading.Thread.__init__(self)
       self.conn = conn
       print("New connection added", Address)
   def run(self):
       print ("Connection from : ", Address)
       self.conn.send(bytes("You are connected to IIT H",'utf-8'))


class RecieveThread(threading.Thread):       ############# this thread takes care about recieving the contents of the .txt file 
   def __init__(self,conn,Address):                 ##      from #######  Client_1 ###########################
      threading.Thread.__init__(self)
      self.conn = conn
   def run(self):
       print("This data is from Housekeeping unit: ",Address)
       data = self.conn.recv(1024).decode()
       print("The wastebin attributes are:  ",  data)


class SendThread(threading.Thread):
   def __init__(self,conn,Address):
       threading.Thread.__init__(self)      ##### This thread takes care about sending the the recieved contents to ## Client_2 #####
       self.conn = conn
   def run(self):
       data = self.conn.recv(1024).decode()
       print("Sending this data to mobile unit")
       self.conn.send(data.encode())




host = ''    #########  Getting the hostname #######      
port = 5000                ###### Fixing the port ##########
server_socket = socket.socket()                ######### initiate the socket #########
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ###### Allows to bind to exacly the same port and IP address#####
server_socket.bind((host, port))   ###### binding the host and the port #######

print("The IIT-H server is active")
print("Waiting for clients to connect")   

while True:

    server_socket.listen(4)    ###### allowing only 4 clients to be in queue to connect ######
    conn, Address = server_socket.accept()   ###### accepting the connections #########
    ClientThread(conn,Address).start()    ##### Calling the first thread class #####
    RecieveThread(conn,Address).start()   ###### Calling the second thread class ######## 
    SendThread(conn,Address).start() ###### Calling the third thread classs ##########  

conn.close()       #### closing the connection ######

Код клиента_1

import socket


host = socket.gethostname()       ############### as both code is running on same pc ###################3
port = 5000                       ############# socket server port number################33

client_socket = socket.socket()               ################# initiate the connection ##########e
client_socket.connect((host, port))

in_data = client_socket.recv(1024).decode()       ############### connect to the server########################
print("From IIT-H server: ", in_data)    
wastebin_attr = open("/Users/sayantanmandal/Python Programs/Waste_data.txt", 'r')   ######### Opening the .txt file ########

wa = wastebin_attr.read()                                      ############ Reading the .txt file ##################


message = wa      

client_socket.send(message.encode()) ########## sending the  message from socket point but before encoding in bytes #########

client_socket.close()               ################### closing the connection ######################

Клиент_2 код

import socket


host = socket.gethostname() 
             ############### as both code is running on same pc ###################3

port = 5000                       ############# socket server port number################33

client_socket = socket.socket()               ################# initiate the connection ##########e
client_socket.connect((host, port))       ############### connect to the server########################


in_data = client_socket.recv(1024).decode()



print("From IIT-H server: ", in_data)

data = client_socket.recv(1024).decode()

print("From Housekeeping unit: ", data)

client_socket.close()               ################### closing the connection ######################

.txt файл, который я использую

1. Wastebin serial number:   
2. Wastebin type:
3. Wastebin status:
4. Wastebin action:
5. Wastebin zone: 
6. Wastebin Lat./Long. :

Пожалуйста, помогите мне, как я могу преодолеть эту ситуацию. Спасибо всем.

...