python socket select timeout example

본 포스트는 python socket에서 리눅스의 select와 동일한 기능을 하는 select 모듈 사용 예제를 싣고 있다.

이전 포스트에서 non-blocking socket 프로그래밍에 대해 알아봤었다. 아래 링크의 포스트에서 만들어진 예제에 'select' 모듈을 추가해 예제 코드를 만들었다.

python socket API 와 non-blocking socket server client example code


1. python socket select timeout example


이전 포스트의 클라이언트 코드에서 select를 사용하지 않은 코드는 아래와 같다.

import socket
import time
def recv(sock,size,timeout_ms):

    while timeout_ms > 0:
        try:
            data = sock.recv(size)
            if data is not None:
                return data.decode()
        except BlockingIOError:
            timeout_ms -= 1
            time.sleep(0.001)
        
    return None

위 코드를 수정해 select를 사용하면 아래와 같이 구현할 수 있다.

import socket
import select

def recv_select(sock,size,timeout_sec):

    r,w,x = select.select([sock,],[],[],timeout_sec)        
    
    if len(r) <= 0: #timeout
        return None
    
    if r[0].getsockname() != sock.getsockname():
        return None
    
    try:
        data = sock.recv(size)
        if data is not None:
            return data.decode()
    except BlockingIOError:
        return None
        
    return None

2. python select API

import select
select.select(rlist, wlist, xlist[, timeout])

arguments:
    rlist : 읽기 준비를 기다릴 파일 디스크립터 리스트. file, sockt 등.
    wlist : 쓰기 준비를 기다릴 파일 디스크립터 리스트.
    xlist : exception 상태를 기다릴 파일 디스트립터 리스트.
    timeout : 대기 시간. 단위 초.

return:
    준비된 디스트립터 리스트를 반환한다. 만약 timeout이 지나면, 빈 리스트를 반환한다.


3. select example code

# socket에서 데이터를 읽을 수 있는 상태를 기다린다. 
r,w,x = select.select([sock,],[],[],timeout_sec)        
    
if len(r) <= 0:
    # timeout인 경우, 빈 리스트를 반환 한다.
    return None

# 읽을 수 있는 상태가 되면,
# select.select([sock,],[],[],timeout_sec) 는  [socket][][]을 반환한다. 
if r[0].getsockname() != sock.getsockname():
    return None

data = sock.recv(size)


댓글

이 블로그의 인기 게시물

간단한 cfar 알고리즘에 대해

windows에서 간단하게 크롬캐스트(Chromecast)를 통해 윈도우 화면 미러링 방법

python ctypes LoadLibrary로 windows dll 로드 및 함수 호출 예제

아두이노(arduino) 심박센서 (heart rate sensor) 심박수 측정 example code

base64 인코딩 디코딩 예제 c 소스