溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

Python編程scoketServer如何實(shí)現(xiàn)多線(xiàn)程同步

發(fā)布時(shí)間:2021-07-22 09:56:51 來(lái)源:億速云 閱讀:179 作者:小新 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要介紹Python編程scoketServer如何實(shí)現(xiàn)多線(xiàn)程同步,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

具體介紹如下。

開(kāi)發(fā)過(guò)程中,為了實(shí)現(xiàn)不同的客戶(hù)端同一時(shí)刻只能有一個(gè)使用共同數(shù)據(jù)。

雖說(shuō)用Python編寫(xiě)簡(jiǎn)單的網(wǎng)絡(luò)程序很方便,但復(fù)雜一點(diǎn)的網(wǎng)絡(luò)程序還是用現(xiàn)成的框架比較好。這樣就可以專(zhuān)心事務(wù)邏輯,而不是套接字的各種細(xì)節(jié)。SocketServer模塊簡(jiǎn)化了編寫(xiě)網(wǎng)絡(luò)服務(wù)程序的任務(wù)。同時(shí)SocketServer模塊也是Python標(biāo)準(zhǔn)庫(kù)中很多服務(wù)器框架的基礎(chǔ)。

網(wǎng)絡(luò)服務(wù)類(lèi):

SocketServer提供了4個(gè)基本的服務(wù)類(lèi):

TCPServer針對(duì)TCP套接字流
UDPServer針對(duì)UDP數(shù)據(jù)報(bào)套接字
UnixStreamServer和UnixDatagramServer針對(duì)UNIX域套接字,不常用。

首先,明確一點(diǎn),在scoketServer中,每當(dāng)有一個(gè)客戶(hù)端連接成功后都會(huì)為每個(gè)客戶(hù)端創(chuàng)建一個(gè)線(xiàn)程。

為了讓這些多線(xiàn)程之間能夠同步執(zhí)行,我的做法是:再創(chuàng)建一個(gè)線(xiàn)程類(lèi),這個(gè)線(xiàn)程類(lèi)中做一些我的項(xiàng)目需要做的事情,,當(dāng)某個(gè)客戶(hù)端想成使用到這個(gè)線(xiàn)程時(shí),給當(dāng)前線(xiàn)程加鎖,運(yùn)行完成后釋放鎖。

請(qǐng)指教

詳細(xì)步驟請(qǐng)看注釋?zhuān)?/strong>

#coding=gbk
__author__ = 'kaikai'

import Queue
import threading
import time
import SocketServer

#全局線(xiàn)程鎖
threadLock = threading.Lock()#全局?jǐn)?shù)據(jù)隊(duì)列
data = Queue.Queue()
#工作線(xiàn)程類(lèi),
class testThead(threading.Thread):
  global data
 def __init__(self):
    threading.Thread.__init__(self)

  def begin_test(self):
    self.start()

  def run(self):
    global threadLock
    
    threadLock.acquire()

    # 從隊(duì)列中取出連接和數(shù)據(jù)
    if data.qsize()>0:
      this_receive = data.get()
    else:
      print "data size is empty !"
      return

    # 解析數(shù)據(jù),獲得連接和數(shù)據(jù)
    # 使用當(dāng)前數(shù)據(jù)的conn
    this_conn = this_receive.keys()[0]
    this_data = this_receive[this_conn]

    # 釋放鎖
    threadLock.release()

  def send_msg(self,conn,msg):
    try:
      conn.sendall(msg)
    except Exception as e:
      print "send " + str(msg) +"fail !!!!!!!!!!!!!!"

  def recv_msg(self,conn):
    try:
      recv_msg = conn.recv(2048)
      return recv_msg
    except Exception as e:

      print " recv msg fail !!!!!!!!!!"
      return None

# 每有一個(gè)客戶(hù)端生成一個(gè)線(xiàn)程。所有線(xiàn)程調(diào)用同一個(gè)測(cè)試線(xiàn)程,如果測(cè)試線(xiàn)程在鎖定中,則進(jìn)入等待。
class MyServer(SocketServer.BaseRequestHandler):

  def send_msg(self,conn,msg):
    try:
      conn.sendall(msg)
    except Exception as e:
      print "send " + str(msg) +"fail !!!!!!!!!!!!!!"
  def recv_msg(self,conn):
    try:
      recv_msg = conn.recv(2048)
      return recv_msg
    except Exception as e:

      print " recv msg fail !!!!!!!!!!"

  def handle(self):
    global data
    # 獲得連接
    conn = self.request

    print "client connect!"

    # 循環(huán)接受客戶(hù)端數(shù)據(jù)
    while True:
      # 接受客戶(hù)端發(fā)送過(guò)來(lái)的參數(shù)
      receive_data = self.recv_msg(conn)

      print receive_data
      # 如果參數(shù)為空,返回報(bào)錯(cuò) 結(jié)束循環(huán)
      if not receive_data:
        print "can not get data form client ! "
        break

      print "data size put before: " + str(data.qsize())
      # 將連接和數(shù)據(jù)添加到隊(duì)列中 放入連接可以保證在另一個(gè)線(xiàn)程中直接使用連接給相應(yīng)客戶(hù)端發(fā)送或者接受數(shù)據(jù)。同時(shí)保證數(shù)據(jù)與客戶(hù)端的一一對(duì)應(yīng)
      data.put({conn:receive_data})

      print "data size put aftter: " + str(data.qsize())
      # 初始化測(cè)試線(xiàn)程
      testThead_this = testThead()
      # 開(kāi)始測(cè)試線(xiàn)程
      testThead_this.begin_test()
      # testThead_this.start()
      # 等待測(cè)試線(xiàn)程執(zhí)行結(jié)束
      testThead_this.join()

      print "this test end "

if __name__ == "__main__" :
  try:
    server = SocketServer.ThreadingTCPServer(('192.168.100.100',56780),MyServer)
    server.timeout = 100
    print "Server run success !!!! "

    server.serve_forever()

  except Exception as e:
    print "Server run failed !!!!\n  error: " + str(e)

以上是“Python編程scoketServer如何實(shí)現(xiàn)多線(xiàn)程同步”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI