본문 바로가기
정보보안

소켓 프로그래밍 핵심 개념 및 실습 예시 🧑‍💻

by 노아입니다 2025. 6. 2.

1. TCP/IP 프로토콜 🌐

설명:
TCP/IP는 인터넷에서 데이터를 주고받는 규칙(프로토콜)의 집합입니다. TCP는 연결을 먼저 맺어 데이터가 순서대로 정확히 도착하도록 보장하며, IP는 데이터를 목적지 컴퓨터까지 전달하는 역할을 합니다.


2. 소켓(Socket) 💡

설명:
소켓은 네트워크 통신을 위한 소프트웨어적 접속점입니다. IP 주소와 포트 번호가 결합되어 특정 프로그램 간 데이터 송수신 통로를 만듭니다.


3. 주요 소켓 함수 및 역할 ⚙️

함수명 설명 사용 위치
socket() 통신용 소켓 생성 서버/클라이언트 모두
bind() 소켓에 IP주소와 포트 할당 서버
listen() 클라이언트 연결 대기 상태로 전환 서버
accept() 클라이언트 연결 수락, 새 소켓 생성 서버
connect() 서버에 연결 요청 클라이언트
send() 데이터 전송 서버/클라이언트 모두
recv() 데이터 수신 서버/클라이언트 모두
close() 소켓 연결 종료 서버/클라이언트 모두

4. 에코 서버 (Python) - 서버 코드

import socket

def echo_server():
    server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_sock.bind(('localhost', 12345))
    server_sock.listen(1)
    print("서버 시작, 연결 대기 중...")

    conn, addr = server_sock.accept()
    print(f"클라이언트 연결됨: {addr}")

    while True:
        data = conn.recv(1024)
        if not data:
            break
        print(f"받은 데이터: {data.decode()}")
        conn.sendall(data)  # 받은 데이터를 그대로 다시 보냄

    conn.close()
    server_sock.close()

if __name__ == '__main__':
    echo_server()

5. 에코 클라이언트 (Python) - 클라이언트 코드

import socket

def echo_client():
    client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_sock.connect(('localhost', 12345))

    message = input("서버에 보낼 메시지 입력: ")
    client_sock.sendall(message.encode())

    data = client_sock.recv(1024)
    print(f"서버로부터 받은 메시지: {data.decode()}")

    client_sock.close()

if __name__ == '__main__':
    echo_client()

6. 멀티쓰레드 에코 서버 (Python)

import socket
import threading

def handle_client(conn, addr):
    print(f"클라이언트 접속: {addr}")
    while True:
        data = conn.recv(1024)
        if not data:
            break
        conn.sendall(data)
    conn.close()
    print(f"클라이언트 연결 종료: {addr}")

def multi_threaded_server():
    server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_sock.bind(('localhost', 12345))
    server_sock.listen()
    print("멀티쓰레드 서버 시작...")

    while True:
        conn, addr = server_sock.accept()
        thread = threading.Thread(target=handle_client, args=(conn, addr))
        thread.start()

if __name__ == '__main__':
    multi_threaded_server()

7. 간단한 채팅 서버 (Python)

import socket
import threading

clients = []

def broadcast(message, sender):
    for client in clients:
        if client != sender:
            client.send(message)

def handle_client(conn):
    while True:
        try:
            message = conn.recv(1024)
            if not message:
                break
            broadcast(message, conn)
        except:
            break
    clients.remove(conn)
    conn.close()

def chat_server():
    server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_sock.bind(('localhost', 12345))
    server_sock.listen()
    print("채팅 서버 시작")

    while True:
        conn, addr = server_sock.accept()
        clients.append(conn)
        threading.Thread(target=handle_client, args=(conn,)).start()

if __name__ == '__main__':
    chat_server()