python3+PyQt5 创建多线程网络应用-TCP客户端和TCP服务器实例

本文在上文的基础上重新实现支持多线程的服务器。

以下为TCP客户端的程序代码:

#!/usr/bin/env python3

import sys
from PyQt5.QtCore import (QByteArray, QDataStream, QDate, QIODevice,
    QRegExp, Qt)
from PyQt5.QtWidgets import (QApplication, QDateEdit, QFrame, QGridLayout,
    QHBoxLayout, QLabel, QLineEdit, QPushButton,
    QWidget)
from PyQt5.QtGui import QRegExpValidator
from PyQt5.QtNetwork import (QTcpSocket,)

MAC = True
try:
  from PyQt5.QtGui import qt_mac_set_native_menubar
except ImportError:
  MAC = False

PORT = 9407
SIZEOF_UINT16 = 2

class BuildingServicesClient(QWidget):

  def __init__(self, parent=None):
    super(BuildingServicesClient, self).__init__(parent)

    self.socket = QTcpSocket()
    self.nextBlockSize = 0
    self.request = None

    roomLabel = QLabel("&Room")
    self.roomEdit = QLineEdit()
    roomLabel.setBuddy(self.roomEdit)
    regex = QRegExp(r"[0-9](?:0[1-9]|[12][0-9]|3[0-4])")
    self.roomEdit.setValidator(QRegExpValidator(regex, self))
    self.roomEdit.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
    dateLabel = QLabel("&Date")
    self.dateEdit = QDateEdit()
    dateLabel.setBuddy(self.dateEdit)
    self.dateEdit.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
    self.dateEdit.setDate(QDate.currentDate().addDays(1))
    self.dateEdit.setDisplayFormat("yyyy-MM-dd")
    responseLabel = QLabel("Response")
    self.responseLabel = QLabel()
    self.responseLabel.setFrameStyle(QFrame.StyledPanel|QFrame.Sunken)

    self.bookButton = QPushButton("&Book")
    self.bookButton.setEnabled(False)
    self.unBookButton = QPushButton("&Unbook")
    self.unBookButton.setEnabled(False)
    quitButton = QPushButton("&Quit")
    if not MAC:
      self.bookButton.setFocusPolicy(Qt.NoFocus)
      self.unBookButton.setFocusPolicy(Qt.NoFocus)

    buttonLayout = QHBoxLayout()
    buttonLayout.addWidget(self.bookButton)
    buttonLayout.addWidget(self.unBookButton)
    buttonLayout.addStretch()
    buttonLayout.addWidget(quitButton)
    layout = QGridLayout()
    layout.addWidget(roomLabel, 0, 0)
    layout.addWidget(self.roomEdit, 0, 1)
    layout.addWidget(dateLabel, 0, 2)
    layout.addWidget(self.dateEdit, 0, 3)
    layout.addWidget(responseLabel, 1, 0)
    layout.addWidget(self.responseLabel, 1, 1, 1, 3)
    layout.addLayout(buttonLayout, 2, 1, 1, 4)
    self.setLayout(layout)

    self.socket.connected.connect(self.sendRequest)
    self.socket.readyRead.connect(self.readResponse)
    self.socket.disconnected.connect(self.serverHasStopped)
    #self.connect(self.socket,
    #       SIGNAL("error(QAbstractSocket::SocketError)"),
     #      self.serverHasError)
    self.socket.error.connect(self.serverHasError)
    self.roomEdit.textEdited.connect(self.updateUi)
    self.dateEdit.dateChanged.connect(self.updateUi)

    self.bookButton.clicked.connect(self.book)
    self.unBookButton.clicked.connect(self.unBook)
    quitButton.clicked.connect(self.close)

    self.setWindowTitle("Building Services")

  def updateUi(self):
    enabled = False
    if (self.roomEdit.text() and
      self.dateEdit.date() > QDate.currentDate()):
      enabled = True
    if self.request is not None:
      enabled = False
    self.bookButton.setEnabled(enabled)
    self.unBookButton.setEnabled(enabled)

  def closeEvent(self, event):
    self.socket.close()
    event.accept()

  def book(self):
    self.issueRequest("BOOK", self.roomEdit.text(),
             self.dateEdit.date())

  def unBook(self):
    self.issueRequest("UNBOOK", self.roomEdit.text(),
             self.dateEdit.date())

  def issueRequest(self, action, room, date):
    self.request = QByteArray()
    stream = QDataStream(self.request, QIODevice.WriteOnly)
    stream.setVersion(QDataStream.Qt_5_7)
    stream.writeUInt16(0)
    stream.writeQString(action)
    stream.writeQString(room)
    stream << date
    stream.device().seek(0)
    stream.writeUInt16(self.request.size() - SIZEOF_UINT16)#overwrite seek(0)
    self.updateUi()
    if self.socket.isOpen():
      self.socket.close()
    self.responseLabel.setText("Connecting to server...")
    self.socket.connectToHost("localhost", PORT)

  def sendRequest(self):
    self.responseLabel.setText("Sending request...")
    self.nextBlockSize = 0
    self.socket.write(self.request)
    self.request = None

  def readResponse(self):
    stream = QDataStream(self.socket)
    stream.setVersion(QDataStream.Qt_5_7)

    while True:
      if self.nextBlockSize == 0:
        if self.socket.bytesAvailable() < SIZEOF_UINT16:
          break
        self.nextBlockSize = stream.readUInt16()
      if self.socket.bytesAvailable() < self.nextBlockSize:
        break
      action = ""
      room = ""
      date = QDate()
      #stream >> action >> room
      action=stream.readQString()
      room=stream.readQString()
      if action != "ERROR":
        stream >> date
      if action == "ERROR":
        msg = "Error: {0}".format(room)
      elif action == "BOOK":
        msg = "Booked room {0} for {1}".format(room,date.toString(Qt.ISODate))
      elif action == "UNBOOK":
        msg = "Unbooked room {0} for {1}".format(room,date.toString(Qt.ISODate))
      self.responseLabel.setText(msg)
      self.updateUi()
      self.nextBlockSize = 0

  def serverHasStopped(self):
    self.responseLabel.setText(
        "Error: Connection closed by server")
    self.socket.close()

  def serverHasError(self, error):
    self.responseLabel.setText("Error: {0}".format(self.socket.errorString()))
    self.socket.close()

app = QApplication(sys.argv)
form = BuildingServicesClient()
form.show()
app.exec_()

以下为TCP服务端的程序代码:

#!/usr/bin/env python3
import bisect
import collections
import sys
from PyQt5.QtCore import (QByteArray, QDataStream, QDate, QReadWriteLock, QThread,QIODevice, Qt)
from PyQt5.QtWidgets import (QApplication, QMessageBox, QPushButton)
from PyQt5.QtNetwork import (QAbstractSocket,QHostAddress, QTcpServer, QTcpSocket)

PORT = 9407
SIZEOF_UINT16 = 2
MAX_BOOKINGS_PER_DAY = 5

# Key = date, value = list of room IDs
Bookings = collections.defaultdict(list)

def printBookings():
  for key in sorted(Bookings):
    print(key, Bookings[key])
  print()

class Thread(QThread):

  lock = QReadWriteLock()

  def __init__(self, socketId, parent):
    super(Thread, self).__init__(parent)
    self.socketId = socketId

  def run(self):
    socket = QTcpSocket()
    if not socket.setSocketDescriptor(self.socketId):
      #self.emit(SIGNAL("error(int)"), socket.error())
      self.error.connect(socket.error)
      return
    while socket.state() == QAbstractSocket.ConnectedState:
      nextBlockSize = 0
      stream = QDataStream(socket)
      stream.setVersion(QDataStream.Qt_5_7)
      if (socket.waitForReadyRead() and
        socket.bytesAvailable() >= SIZEOF_UINT16):
        nextBlockSize = stream.readUInt16()
      else:
        self.sendError(socket, "Cannot read client request")
        return
      if socket.bytesAvailable() < nextBlockSize:
        if (not socket.waitForReadyRead(60000) or
          socket.bytesAvailable() < nextBlockSize):
          self.sendError(socket, "Cannot read client data")
          return
      action = ""
      room = ""
      date = QDate()
      action=stream.readQString()
      if action in ("BOOK", "UNBOOK"):
        room=stream.readQString()
        stream >> date
        try:
          Thread.lock.lockForRead()
          bookings = Bookings.get(date.toPyDate())
        finally:
          Thread.lock.unlock()
        uroom = str(room)
      if action == "BOOK":
        newlist = False
        try:
          Thread.lock.lockForRead()
          if bookings is None:
            newlist = True
        finally:
          Thread.lock.unlock()
        if newlist:
          try:
            Thread.lock.lockForWrite()
            bookings = Bookings[date.toPyDate()]
          finally:
            Thread.lock.unlock()
        error = None
        insert = False
        try:
          Thread.lock.lockForRead()
          if len(bookings) < MAX_BOOKINGS_PER_DAY:
            if uroom in bookings:
              error = "Cannot accept duplicate booking"
            else:
              insert = True
          else:
            error = "{0} is fully booked".format(date.toString(Qt.ISODate))
        finally:
          Thread.lock.unlock()
        if insert:
          try:
            Thread.lock.lockForWrite()
            bisect.insort(bookings, uroom)
          finally:
            Thread.lock.unlock()
          self.sendReply(socket, action, room, date)
        else:
          self.sendError(socket, error)
      elif action == "UNBOOK":
        error = None
        remove = False
        try:
          Thread.lock.lockForRead()
          if bookings is None or uroom not in bookings:
            error = "Cannot unbook nonexistent booking"
          else:
            remove = True
        finally:
          Thread.lock.unlock()
        if remove:
          try:
            Thread.lock.lockForWrite()
            bookings.remove(uroom)
          finally:
            Thread.lock.unlock()
          self.sendReply(socket, action, room, date)
        else:
          self.sendError(socket, error)
      else:
        self.sendError(socket, "Unrecognized request")
      socket.waitForDisconnected()
      try:
        Thread.lock.lockForRead()
        printBookings()
      finally:
        Thread.lock.unlock()

  def sendError(self, socket, msg):
    reply = QByteArray()
    stream = QDataStream(reply, QIODevice.WriteOnly)
    stream.setVersion(QDataStream.Qt_5_7)
    stream.writeUInt16(0)
    stream.writeQString("ERROR")
    stream.writeQString(msg)
    stream.device().seek(0)
    stream.writeUInt16(reply.size() - SIZEOF_UINT16)
    socket.write(reply)

  def sendReply(self, socket, action, room, date):
    reply = QByteArray()
    stream = QDataStream(reply, QIODevice.WriteOnly)
    stream.setVersion(QDataStream.Qt_5_7)
    stream.writeUInt16(0)
    stream.writeQString(action)
    stream.writeQString(room)
    stream<<date
    stream.device().seek(0)
    stream.writeUInt16(reply.size() - SIZEOF_UINT16)
    socket.write(reply)

class TcpServer(QTcpServer):

  def __init__(self, parent=None):
    super(TcpServer, self).__init__(parent)

  def incomingConnection(self, socketId):
    thread = Thread(socketId, self)
    #self.connect(thread, SIGNAL("finished()"),
    #       thread, SLOT("deleteLater()"))
    thread.finished.connect(thread.deleteLater)
    thread.start()

class BuildingServicesDlg(QPushButton):

  def __init__(self, parent=None):
    super(BuildingServicesDlg, self).__init__(
        "&Close Server", parent)
    self.setWindowFlags(Qt.WindowStaysOnTopHint)

    self.loadBookings()
    self.tcpServer = TcpServer(self)
    if not self.tcpServer.listen(QHostAddress("0.0.0.0"), PORT):
      QMessageBox.critical(self, "Building Services Server","Failed to start server: {0}".format(self.tcpServer.errorString()))
      self.close()
      return

    self.clicked.connect(self.close)
    font = self.font()
    font.setPointSize(24)
    self.setFont(font)
    self.setWindowTitle("Building Services Server")

  def loadBookings(self):
    # Generate fake data
    import random

    today = QDate.currentDate()
    for i in range(10):
      date = today.addDays(random.randint(7, 60))
      for j in range(random.randint(1, MAX_BOOKINGS_PER_DAY)):
        # Rooms are 001..534 excl. 100, 200, ..., 500
        floor = random.randint(0, 5)
        room = random.randint(1, 34)
        bookings = Bookings[date.toPyDate()]
        if len(bookings) >= MAX_BOOKINGS_PER_DAY:
          continue
        bisect.insort(bookings, "{0:1d}{1:02d}".format(
               floor, room))
    printBookings()

app = QApplication(sys.argv)
form = BuildingServicesDlg()
form.show()
form.move(0, 0)
app.exec_()

以上这篇python3+PyQt5 创建多线程网络应用-TCP客户端和TCP服务器实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • python3+PyQt5实现支持多线程的页面索引器应用程序

    本文通过Python3+pyqt5实现了python Qt GUI 快速编程的19章的页面索引器应用程序例子. /home/yrd/eric_workspace/chap19/walker_ans.py #!/usr/bin/env python3 import codecs import html.entities import re import sys from PyQt5.QtCore import (QMutex, QThread,pyqtSignal,Qt) class Walker

  • 用Python实现一个简单的多线程TCP服务器的教程

    最近看<python核心编程>,书中实现了一个简单的1对1的TCPserver,但是在实际使用中1对1的形势明显是不行的,所以研究了一下如何在server端通过启动不同的线程(进程)来实现每个链接一个线程. 其实python在类的设计上已经考虑到了这一方面的需求,我们只要在自己的server上继承一下SocketServer.BaseRequestHandler就可以了. server端代码如下: #!/usr/bin/env python import SocketServer from t

  • python3实现TCP协议的简单服务器和客户端案例(分享)

    利用python3来实现TCP协议,和UDP类似.UDP应用于及时通信,而TCP协议用来传送文件.命令等操作,因为这些数据不允许丢失,否则会造成文件错误或命令混乱.下面代码就是模拟客户端通过命令行操作服务器.客户端输入命令,服务器执行并且返回结果. TCP(Transmission Control Protocol 传输控制协议):是一种面向连接的.可靠的.基于字节流的传输层通信协议,由IETF的RFC 793定义. TCP客户端 from socket import * host = '192

  • python如何创建TCP服务端和客户端

    本文实例为大家分享了python创建tcp服务端和客户端的具体代码,供大家参考,具体内容如下 1.服务端server from socket import * from time import ctime HOST = '' PORT = 9999 BUFSIZ = 1024 ADDR = (HOST, PORT) tcpSerSock = socket(AF_INET, SOCK_STREAM) #创建套接字 tcpSerSock.bind(ADDR) #绑定IP和端口 tcpSerSock.

  • python使用socket创建tcp服务器和客户端

    python使用socket创建tcp服务器和客户端. 服务器端为一个时间戳服务器,在接收到客户端发来的数据后,自动回复. 客户端,等待用户输入,回车后向服务器发送用户输入的内容. 分别在python2.7和python3.6下测试.在启动时需要先启动服务器端,在启动客户端. python2.7下 服务器端代码为 #coding:utf-8 from socket import * from time import ctime print("=====================时间戳TCP

  • python实现TCP服务器端与客户端的方法详解

    本文实例讲述了python实现TCP服务器端与客户端的方法.分享给大家供大家参考.具体如下: TCP服务器程序(tsTserv.py): from socket import * from time import ctime HOST = '' PORT = 21567 BUFSIZ = 1024 ADDR = (HOST, PORT) tcpSerSock = socket(AF_INET, SOCK_STREAM) tcpSerSock.bind(ADDR) tcpSerSock.liste

  • python网络编程之TCP通信实例和socketserver框架使用例子

    1.TCP是一种面向连接的可靠地协议,在一方发送数据之前,必须在双方之间建立一个连接,建立的过程需要经过三次握手,通信完成后要拆除连接,需要经过四次握手,这是由TCP的半关闭造成的,一方在完成数据发送后要发送一个FIN来终止这个方向的连接,一个TCP连接在收到一个FIN后仍能发送数据,但应用程序很少这么做,下面是TCP连接建立和拆除的过程: 2.python可以实现TCP服务器和客户端的编程,下面是代码: 服务器端: 复制代码 代码如下: #!/usr/bin/env pythonimport

  • python3+PyQt5 创建多线程网络应用-TCP客户端和TCP服务器实例

    本文在上文的基础上重新实现支持多线程的服务器. 以下为TCP客户端的程序代码: #!/usr/bin/env python3 import sys from PyQt5.QtCore import (QByteArray, QDataStream, QDate, QIODevice, QRegExp, Qt) from PyQt5.QtWidgets import (QApplication, QDateEdit, QFrame, QGridLayout, QHBoxLayout, QLabel

  • python3+PyQt5重新实现QT事件处理程序

    本文是对<Python Qt GUI快速编程>的第10章的例子events用Python3+PyQt5进行改写,涉及到重新实现QWidget的事件处理程序.本例子涉及到上下文菜单,鼠标事件,键盘事件,可作为重新实现事件处理程序的参考. 注:在创建上下文菜单最简单的方式使用Qwidget.addAction()把动作添加到窗口部件中,再把窗口部件的上下文菜单策略设置为Qt.ActionsContextMenu即可,但是如果像本例子一样要根据不同的状态来提供不同的选项,则要重新实现上下文菜单事件处

  • python3+PyQt5重新实现自定义数据拖放处理

    本文分成两部分,第一部分通过python3+PyQt5实现自定义数据的拖放操作.第二部分则对第一部分的程序进行修改,增加拖放操作时,菜单提示是否移动或拷贝,还有可以通过ctrl键盘来设置移动过程中拷贝源而非会将源删除. 自定义数据MIME数据类型QMimeData,MIME是一种用于处理具有多个组成部分的自定义数据的标准化格式.MIME数据由一个数据类型和一个子类型构成–例如,text/plain,text/html,image/png,要处理自定义MIME数据,就必须要选用一种自定义数据类型和

  • python3+PyQt5泛型委托详解

    自定义委托可以让我们对视图中出现的数据项的外观和行为进行完全控制.如果有很多模型,可能会希望不是全部的大多数模型能够仅用一个自定义委托,如果不能这么做,那么对于这些自定义委托,将很有可能存在大量重复代码.为了使得维护工作变得轻松,更好的方法为不要为每个模型创建一个自定义委托,而是用一系列的通用组件来共同构成一个委托.本文通过Python3+pyqt5实现了python Qt GUI 快速编程的16章的泛型委托例子. /home/yrd/eric_workspace/chap16/richtext

  • Pyqt5 实现多线程文件搜索的案例

    我学Java的时候也用Swing做了一个文件搜索的小程序,但界面真的挺丑的,现在学了点python,感觉python是最简单的语言,没有之一. (大家没事都可以来学的,真的很简单有趣哦) 我采用的是pyqt5,所以需要先安装Pyqt5模块 直接cmd命令输入 pip install pyqt5 闲言少叙,上代码!! # -*- coding: utf-8 -*- # @Time : 2018\9\15 20:39 # @Author : Tang weiyang # @File : FileSe

  • Java创建多线程局域网聊天室实例

    局域网聊天室 在学习了一个学期的java以后,觉得java真是博大精深,彻底放弃了因为c++而轻视java的心态,搞了一个多线程的聊天室,熟悉了一下服务器和客户机的操作. 1.TCP 要实现局域网连接,就必须知道信息传输的原理. 在局域网里面传输的信息都是以包的形式,我使用的TCP包传输数据,TCP包里面封装了IP报文. 下面这句话就是通过一个静态IPV4协议的类得到一个服务器的IP地址. address = InetAddress.getByName("192.168.43.86")

  • Android编程实现TCP客户端的方法

    本文实例讲述了Android编程实现TCP客户端的方法.分享给大家供大家参考,具体如下: 因为项目上需要实现一个TCP Client 端:在网上找好多例子基本上都是阻塞方式完成: 我的实现例子:由Activity 及sever 来实现,在sever 创建一个线程来监听接受数据.收到数据,通过广播发送给Activity; 服务端我没有去实现,你可以下载TCP Socket 调试工具v2.2:创建个9005端口:客户端:访问的IP为10.0.2.2 AnetTest.java: /** * Copy

  • java 中模拟TCP传输的客户端和服务端实例详解

    一.创建TCP传输的客户端 1.建立TCP客户端的Socket服务,使用的是Socket对象,建议该对象一创建就明确目的地,即要连接的主机: 2.如果连接建立成功,说明数据传输通道已建立,该通道就是Socket流,是底层建立好的,既然是流,说着这里既有输入流,又有输出流,想要输入流或者输出流对象,可以通过Socket来获取,可以通过getOutputStream()和getInputStream()来获取: 3.使用输出流,将数据写出: 4.关闭Socket服务. import java.io.

随机推荐