[파이썬] PyQt 소켓 프로그래밍 (`QTcpSocket`, `QUdpSocket`)

PyQt is a set of Python bindings for the Qt application framework. It is widely used to create cross-platform desktop applications with beautiful graphical user interfaces. One of the powerful features of PyQt is its support for socket programming. With PyQt’s QTcpSocket and QUdpSocket classes, you can easily create client and server applications that communicate over TCP/IP or UDP protocols.

In this blog post, we will explore the basics of PyQt socket programming using the QTcpSocket and QUdpSocket classes in Python. We will cover how to create a socket, connect to a server, send and receive data, and handle errors.

Setup

Before we begin, make sure you have PyQt installed on your system. You can install PyQt using pip:

pip install pyqt5

QTcpSocket

QTcpSocket is a class that provides a TCP socket. It allows you to create a TCP client or server application.

TCP Client Example

from PyQt5.QtCore import QIODevice, QTimer
from PyQt5.QtNetwork import QTcpSocket

# Create a TCP socket
socket = QTcpSocket()

# Connect to a server
socket.connectToHost("localhost", 8080)

# Check if the connection was successful
if socket.waitForConnected(5000):
    print("Connected to the server.")

    # Send data to the server
    socket.write(b"Hello, server!")

    # Wait for the server's response
    if socket.waitForReadyRead(5000):
        response = socket.readAll().data()
        print("Received response from the server:", response.decode())

        # Disconnect from the server
        socket.disconnectFromHost()
else:
    print("Failed to connect to the server:", socket.errorString())

In this example, we create a TCP client using the QTcpSocket class. We then connect to a server running on localhost at port 8080. If the connection is successful, we send a message to the server and wait for its response. Finally, we disconnect from the server.

TCP Server Example

from PyQt5.QtCore import QIODevice
from PyQt5.QtNetwork import QTcpServer

# Create a TCP server
server = QTcpServer()

# Bind the server to a port
if not server.listen("localhost", 8080):
    print("Failed to start the server:", server.errorString())

# Handle new connections
def handle_new_connection():
    socket = server.nextPendingConnection()

    print("New connection:", socket.peerAddress().toString())

    # Read data from the client
    if socket.waitForReadyRead(5000):
        data = socket.readAll().data()
        print("Received data from the client:", data.decode())

        # Send a response back to the client
        socket.write(b"Hello, client!")

    # Disconnect the client
    socket.disconnectFromHost()

# Connect the signal to the slot
server.newConnection.connect(handle_new_connection)

In this example, we create a TCP server using the QTcpServer class. We bind the server to localhost at port 8080. When a new client connects to the server, the handle_new_connection function is called. Inside this function, we read data from the client, send a response, and disconnect the client.

QUdpSocket

QUdpSocket is a class that provides a UDP socket. It allows you to create a UDP client or server application.

UDP Client Example

from PyQt5.QtCore import QByteArray, QIODevice
from PyQt5.QtNetwork import QUdpSocket

# Create a UDP socket
socket = QUdpSocket()

# Send data to a server
message = QByteArray(b"Hello, server!")
socket.writeDatagram(message, "localhost", 8080)

In this example, we create a UDP client using the QUdpSocket class. We then send a message to a server running on localhost at port 8080.

UDP Server Example

from PyQt5.QtCore import QIODevice
from PyQt5.QtNetwork import QUdpSocket

# Create a UDP socket
socket = QUdpSocket()

# Bind the socket to a port
if not socket.bind("localhost", 8080):
    print("Failed to bind the socket:", socket.errorString())

# Receive data from clients
while socket.hasPendingDatagrams():
    datagram, host, port = socket.readDatagram(socket.pendingDatagramSize())

    print("Received data from", host.toString(), ":", datagram.data().decode())

In this example, we create a UDP server using the QUdpSocket class. We bind the socket to localhost at port 8080. We then continuously check for pending datagrams (incoming messages) and print the received data along with the client’s address.

Conclusion

PyQt’s QTcpSocket and QUdpSocket classes allow you to incorporate socket programming into your Python applications with ease. With these classes, you can create powerful client and server applications that communicate over TCP/IP or UDP protocols.