【问题标题】:How to run multithreading in python for multi client socket programming?如何在 python 中运行多线程以进行多客户端套接字编程?
【发布时间】:2020-01-27 05:57:06
【问题描述】:

在这段代码中,当我尝试在 python 套接字上不应用多线程时,它工作得非常好。但是在使用多线程并发后,第一个while循环工作正常,但是当第二个while循环没有运行直到我关闭连接时,这样做,它需要第二个while循环作为第二个线程,这没有完成发送过程安卓的密钥。在这里,问题在于第二个循环作为第二个线程。我将如何做到这一点?任何帮助将不胜感激!

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

【问题讨论】:

    标签: python multithreading sockets while-loop


    【解决方案1】:

    我解决了这个问题,因为我的输出也会以我想要的方式出现。解决方案的基本思想如下:-

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-26
      • 2019-01-03
      • 2010-11-25
      • 2021-02-09
      • 1970-01-01
      相关资源
      最近更新 更多