개발 | 프로젝트/Python

[Python] 웹소켓 서버 / 클라이언트 구현 (WebSocket 라이브러리)

seulll 2024. 11. 27. 15:13

python은 웹소켓 개발을 위한 WebSockets 라이브러리를 지원한다.

  • WebSocket 프로토콜은 클라이언트와 서버 간의 양방향 통신을 가능하게 하는 기술로, HTTP 통신의 한계를 넘어 지속적이고 실시간의 데이터 교환을 필요로 하는 애플리케이션에 적합하다. 
  • WebSockets 라이브러리는 이 프로토콜을 쉽게 사용할 수 있게 해주며, 비동기 I/O를 통해 고성능 통신을 구현할 수 있도록 도와준다.

주요 기능

  • 간편한 서버 구축: WebSocket 서버를 쉽게 구축하고 실행할 수 있음
  • 비동기 지원: Python의 asyncio를 활용한 비동기 프로그래밍을 지원하여, 고성능 네트워킹 애플리케이션 개발이 가능
  • 클라이언트 연결 관리: WebSocket 클라이언트를 생성하고, 서버와의 연결을 관리할 수 있음
  • 메시지 핸들링: 텍스트 및 바이너리 메시지를 송수신하는 기능을 제공
  • 보안: SSL/TLS를 통한 암호화된 연결 지원으로 보안성을 강화

라이브러리 설치 

pip install websockets

 

 


간단한 예제 코드

- 웹소켓 서버 

import asyncio
import websockets

async def echo(websocket, path):
    print("클라이언트 연결됨")
    async for message in websocket:
        print(f"클라이언트로부터 메시지: {message}")
        await websocket.send("Hello, Client!") 

start_server = websockets.serve(echo, "localhost", 8765)

asyncio.get_event_loop().run_until_complete(start_server)
print("서버가 시작되었습니다...")
asyncio.get_event_loop().run_forever()

 

 

- 웹소켓 클라이언트

import asyncio
import websockets

async def hello():
    uri = "ws://localhost:8765"  # 서버 주소
    async with websockets.connect(uri) as websocket:
        await websocket.send("Hello, Server!") 
        response = await websocket.recv()  # 서버로부터 응답 받기
        print(f"서버로부터 응답: {response}")

asyncio.get_event_loop().run_until_complete(hello())

 

서버 코드 실행 후 클라이언트 코드를 실행하면 클라이언트가 서버에 메세지를 보내고 서버가 응답하는 과정을 확인할 수 있다.