'HTML'에 해당되는 글 1건

  1. 2023.01.01 python WebSocket Server

WebSockets 설치

파이썬을 구현하기 위해서는 먼저, python과 pip로 websockets 를 설치하셔야합니다.

웹소켓 설치
$ pip install websockets

설치확인
$ pip list

 

웹소켓 서버 코딩

너무 간단해서 사실 놀랐습니다. websockets.serve 함수에 인자로 각각 '실행메소드', 'ip 혹은 주소', 'port'를 넣어주고, 응답을 대기하는 동안 종료되지 않도록. asyncio.get_event_loop().run_until_complete, asyncio.get_event_loop().run_forever를 이용해 실행해 주시면되겠습니다.

서버는 복잡하지 않도록 응답을 그대로 돌려 주는 에코 서버로 만들었습니다. 소스는 아래와 같습니다.

import asyncio;
import websockets;

port = 10000

async def accept(self, path):
    while True:
        data = await self.recv()
        print("receive:" + data)
        send_str = 'echo : ' + data
        await self.send(send_str)
        print('send => ' + send_str)

print("웹소켓 시작 포트넘버:" + str(port))
start_server = websockets.serve(accept, "localhost", port)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
print("End Service!")

 

 

클라이언트 코딩

간단히 html과 javascript를 통해 예제를 만들어 봤습니다. 대체로, websocket.onopen, websocket.onclose 등의 함수를 사용하지만 저는 괄호가 중첩되는 것이 싫어 이벤트 형식으로 만들었습니다.

<title>WebSocket 테스트</title>
<style>
    .spacer {margin-bottom: 1rem;}
</style>

<div class="spacer">
    <span>상태 : </span><span id="status">접속안됨</span>
</div>
<div id="recived" class="spacer" style="height: 15rem; border: #aaa 1px solid; padding: 0.5rem; max-width: 30rem;"></div>
<div class="spacer">
    <input id="message" />
    <button id="send">보내기</button>
    <button id="close">종료</button>
</div>

<script>

    const url = 'ws://localhost:10000';
    const ws = new WebSocket(url);

    const E_Receive = document.querySelector('#recived');
    const E_Message = document.querySelector('#message');
    const E_Status = document.querySelector('#status');
    const E_Btn_Send = document.querySelector('#send');
    const E_Btn_Close = document.querySelector('#close');

    // 웹소켓 이벤트 처리.
    ws.addEventListener("open", e=>{
        E_Status.innerHTML = "접속";
    });
    ws.addEventListener("message", e=>{
        console.log("e",e);
        E_Receive.innerHTML += `<div>수신 : ${e.data}</div>`;
    })

    // ui 이벤트 처리.
    E_Btn_Send.addEventListener('click',e=>{
        if(!E_Message.value) return alert("메세지를 입력하지 않았습니다.");
        E_Receive.innerHTML += `<div>발신 : ${E_Message.value}</div>`;
        ws.send(E_Message.value);
        E_Message.value = "";
    })

    E_Btn_Close.addEventListener('click',e=>{
        ws.close();
        E_Status.innerHTML = "종료";
    });

</script>

 

 

그럼 즐거운 코딩 되시길 바랍니다.

 

 

 

 

 

'파이썬' 카테고리의 다른 글

window 장고설치  (0) 2023.01.02
Posted by 창업닉군
,