脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python编程scoketServer实现多线程同步实例代码

Python编程scoketServer实现多线程同步实例代码

2021-01-10 00:07张开开 Python

这篇文章主要介绍了Python编程scoketServer实现多线程同步实例代码,小编觉得还是挺不错的,具有一定借鉴价值,需要的朋友可以参考下

本文研究的主要是Python编程scoketServer实现多线程同步的相关内容,具体介绍如下。

开发过程中,为了实现不同的客户端同一时刻只能有一个使用共同数据。

虽说用Python编写简单的网络程序很方便,但复杂一点的网络程序还是用现成的框架比较好。这样就可以专心事务逻辑,而不是套接字的各种细节。SocketServer模块简化了编写网络服务程序的任务。同时SocketServer模块也是Python标准库中很多服务器框架的基础。

网络服务类:

SocketServer提供了4个基本的服务类:

TCPServer针对TCP套接字流
UDPServer针对UDP数据报套接字
UnixStreamServer和UnixDatagramServer针对UNIX域套接字,不常用。

首先,明确一点,在scoketServer中,每当有一个客户端连接成功后都会为每个客户端创建一个线程。

为了让这些多线程之间能够同步执行,我的做法是:再创建一个线程类,这个线程类中做一些我的项目需要做的事情,,当某个客户端想成使用到这个线程时,给当前线程加锁,运行完成后释放锁。

请指教

详细步骤请看注释:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#coding=gbk
__author__ = 'kaikai'
 
import Queue
import threading
import time
import SocketServer
 
#全局线程锁
threadLock = threading.Lock()#全局数据队列
data = Queue.Queue()
#工作线程类,
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()
 
    # 从队列中取出连接和数据
    if data.qsize()>0:
      this_receive = data.get()
    else:
      print "data size is empty !"
      return
 
    # 解析数据,获得连接和数据
    # 使用当前数据的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
 
# 每有一个客户端生成一个线程。所有线程调用同一个测试线程,如果测试线程在锁定中,则进入等待。
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!"
 
    # 循环接受客户端数据
    while True:
      # 接受客户端发送过来的参数
      receive_data = self.recv_msg(conn)
 
      print receive_data
      # 如果参数为空,返回报错 结束循环
      if not receive_data:
        print "can not get data form client ! "
        break
 
      print "data size put before: " + str(data.qsize())
      # 将连接和数据添加到队列中 放入连接可以保证在另一个线程中直接使用连接给相应客户端发送或者接受数据。同时保证数据与客户端的一一对应
      data.put({conn:receive_data})
 
      print "data size put aftter: " + str(data.qsize())
      # 初始化测试线程
      testThead_this = testThead()
      # 开始测试线程
      testThead_this.begin_test()
      # testThead_this.start()
      # 等待测试线程执行结束
      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实现多线程同步实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

原文链接:http://www.cnblogs.com/zhangkaikai/p/6605158.html

延伸 · 阅读

精彩推荐