Simple Socket Communication

Listing 26 scripts/PYQT5/02_socket/01_simple_server.py (Server)
# -*- coding: utf-8 -*-

import socket

def main():
    # 소켓 객체 생성
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # IP와 포트를 바인드
    server_socket.bind(('127.0.0.1', 12345))

    # 클라이언트 연결을 기다리기 시작, 동시에 처리할 수 있는 최대 연결 수는 5
    server_socket.listen(5)

    print("Server waiting for a connection...")
    connection, address = server_socket.accept()
    print("Connected by", address)

    while True:
        # 클라이언트로부터 데이터를 받음
        data = connection.recv(1024)

        if not data:
            break

        print("Received:", data.decode())

        # 데이터를 클라이언트로 되돌려줌
        connection.sendall(data)

    connection.close()

if __name__ == "__main__":
    main()

This example uses the socket to create a basic TCP server.

  • socket.AF_INET and socket.SOCK_STREAM are used to specify the IPv4 address scheme and the TCP socket type respectively.

  • The server_socket.bind() method is used to bind an IP address and a port number.

  • While waiting for a client connection, the server receives data and then echoes (returns) it.

Listing 27 scripts/PYQT5/02_socket/02_simple_client.py (Client)
# -*- coding: utf-8 -*-

import socket

def main():
    # 소켓 객체 생성
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 서버에 연결
    client_socket.connect(('127.0.0.1', 12345))

    message = raw_input("Enter your message: ")
    client_socket.sendall(message.encode())

    # 서버로부터 데이터를 받음
    data = client_socket.recv(1024)
    print("Received from server:", data.decode())

    client_socket.close()

if __name__ == "__main__":
    main()

This example demonstrates the creation of a basic TCP client using socket.

  • It sends a message to the server and then receives the same message back from the server.