[파이썬] PyQt 웹 소켓 (`QWebSocket`)

Web sockets are a powerful communication protocol that allows real-time, bidirectional communication between a client and a server over a single, long-lived connection. PyQt, a set of Python bindings for Qt, provides support for web sockets through the QWebSocket class. In this blog post, we will explore how to use PyQt’s QWebSocket to implement web socket communication in a Python application.

Installation

Before we get started, make sure you have PyQt installed. You can install it using pip:

pip install PyQt5

Setting up a WebSocket Server

To begin, let’s set up a simple WebSocket server using PyQt’s QWebSocketServer. The server will listen for incoming connections and handle incoming and outgoing messages. Here’s an example:

from PyQt5.QtCore import QCoreApplication, QObject
from PyQt5.QtNetwork import QHostAddress, QWebSocketServer

class WebSocketServer(QObject):
    def __init__(self, host, port):
        super(WebSocketServer, self).__init__()
        self.server = QWebSocketServer("My WebSocket Server", QWebSocketServer.NonSecureMode, self)
        if not self.server.listen(QHostAddress(host), port):
            print("Failed to start WebSocket server.")
            return
    
        self.server.newConnection.connect(self.handleNewConnection)

    def handleNewConnection(self):
        socket = self.server.nextPendingConnection()
        socket.textMessageReceived.connect(self.handleMessageReceived)
        socket.disconnected.connect(self.handleSocketDisconnected)

    def handleMessageReceived(self, message):
        print("Received message: ", message)

    def handleSocketDisconnected(self):
        socket = self.sender()
        print("Socket disconnected: ", socket.peerAddress().toString())

if __name__ == "__main__":
    app = QCoreApplication([])
    server = WebSocketServer("localhost", 8000)
    app.exec_()

In this code, we create a WebSocketServer class that inherits from QObject and sets up a QWebSocketServer to listen for incoming connections. When a new connection is made, we connect the textMessageReceived and disconnected signals of the socket to their respective slots.

The handleMessageReceived slot is called whenever a new message is received from the client, and the handleSocketDisconnected slot is called when the client disconnects. In this example, we simply print the received messages and the socket’s peer address to the console.

Connecting to the WebSocket Server

Now that we have our server set up, let’s create a client that connects to it and sends messages. We can use PyQt’s QWebSocket for this purpose. Here’s an example:

from PyQt5.QtCore import QCoreApplication, QObject
from PyQt5.QtWebSockets import QWebSocket

class WebSocketClient(QObject):
    def __init__(self, url):
        super(WebSocketClient, self).__init__()
        self.socket = QWebSocket()
        self.socket.connected.connect(self.handleConnected)
        self.socket.textMessageReceived.connect(self.handleMessageReceived)
        self.socket.disconnected.connect(self.handleDisconnected)

        self.socket.open(QUrl(url))    

    def handleConnected(self):
        print("Connected to server.")

    def handleMessageReceived(self, message):
        print("Received message: ", message)

    def handleDisconnected(self):
        print("Disconnected from server.")

if __name__ == "__main__":
    app = QCoreApplication([])
    client = WebSocketClient("ws://localhost:8000")
    app.exec_()

In this code, we create a WebSocketClient class that inherits from QObject and sets up a QWebSocket. We connect the connected, textMessageReceived, and disconnected signals of the socket to their respective slots.

The handleConnected slot is called when the client successfully connects to the server, the handleMessageReceived slot is called when a new message is received, and the handleDisconnected slot is called when the client disconnects.

In this example, we simply print the connection state and the received messages to the console.

Conclusion

In this blog post, we explored how to use PyQt’s QWebSocket to implement web socket communication in a Python application. We saw how to set up a WebSocket server that listens for incoming connections and handles incoming and outgoing messages, as well as how to create a client that connects to the server and sends messages.

Web socket communication can be a powerful tool for real-time, bidirectional communication in your Python applications. PyQt’s QWebSocket provides a convenient way to implement web socket functionality.