기술(Tech, IT)/네트워크 (Networking)

[Networking] Socket Programming (소켓 프로그래밍) - 파이썬 구현

Daniel803 2024. 5. 7. 03:45

가독성과 포괄적인 표준 라이브러리로 인해 널리 사용되는 Python을 사용해 서버와 클라이언트 모두에 대한 Socket Programming의 간단한 예제다. 다음은 TCP 서버와 클라이언트를 설정하는 방법에 대한 기본 예제다. 매우 기본적인 예시이며 실제 애플리케이션에서는 오류, 여러 클라이언트 및 보다 정교한 데이터 처리를 해야한다. 

 

  • TCP Server Code
    : 이 서버는 지정된 호스트와 포트에서 수신 대기하고, 연결을 수락하고, 클라이언트로부터 메시지를 수신한 후 응답을 다시 보냅니다.
import socket

def run_server(host='127.0.0.1', port=65432):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind((host, port))  # Bind to the address and port
        s.listen()            # Listen for incoming connections
        print(f"Server is running and listening at {host}:{port}")
        conn, addr = s.accept()  # Accept a new connection
        with conn:
            print(f"Connected by {addr}")
            while True:
                data = conn.recv(1024)  # Receive data from the client
                if not data:
                    break
                conn.sendall(data)  # Send data back to the client

# To run the server, you would typically call run_server()

 

  • TCP Client Code
    : 이 클라이언트는 지정된 호스트와 포트에 연결하고, 메시지를 송신하며, 응답을 수신한다.
import socket

def run_client(server_host='127.0.0.1', server_port=65432):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((server_host, server_port))  # Connect to the server
        s.sendall(b'Hello, server')  # Send a message to the server
        data = s.recv(1024)  # Receive the response from the server
    print('Received', repr(data))

# To run the client, you would typically call run_client() after the server is running

 

  • 예제 실행 방법
    • 서버를 시작한다
      : 서버 스크립트를 실행한다. 클라이언틔 연결을 기다린다.
    • 클라이언트를 실행한다
      : 서버가 수신 대기 중이면 클라이언트 스크립트를 실행한다. 서버에 연결하고 메시지를 보낸 다음 응답을 인쇄해야 한다.