Created
November 24, 2017 09:37
-
-
Save sooop/9ffc3a6ba8b371d68ec00cafdc875986 to your computer and use it in GitHub Desktop.
파일 개수를 체크하여 클라이언트에게 알려주는 소켓서버 구현
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import socket | |
| def client(): | |
| host, port = '127.0.0.1', 4000 | |
| with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: | |
| s.connect((host, port)) | |
| print(s.recv(4096).decode()) | |
| print(s.recv(4096).decode()) | |
| client() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from threading import Thread | |
| from queue import Queue | |
| import socket | |
| import datetime | |
| import time | |
| import glob | |
| queue = Queue() | |
| ## 새 파일을 감시하는 함수 | |
| def watch(dirname): | |
| fs = set(glob.glob(dirname + '/*')) | |
| while True: | |
| time.sleep(0.5) | |
| new_fs = set(glob.glob(dirname + '/*')) | |
| ds = new_fs - fs | |
| if ds: | |
| for new_file in ds: | |
| queue.put((str(datetime.datetime.now()), new_file)) | |
| fs = new_fs | |
| ## 소켓서버 | |
| def server_routine(): | |
| host, port = '', 4000 | |
| with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: | |
| s.bind((host, port)) | |
| print('run server: 4000') | |
| while True: | |
| s.listen(1) | |
| conn, addr = s.accept() | |
| print('incoming connection...') | |
| with conn: | |
| conn.sendall(f'{queue.qsize()} 파일이 추가되었습니다.'.encode()) | |
| fileinfo = [] | |
| while not queue.empty(): | |
| fileinfo.append(queue.get()) | |
| msg = '\n'.join(f'파일이 추가되었습니다({time}): {filename}'\ | |
| for time, filename in fileinfo) | |
| conn.sendall(msg.encode()) | |
| def main(): | |
| t = Thread(target=watch, args=('e:/temp',)) | |
| t.start() | |
| server_routine() | |
| main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment