Skip to content

Instantly share code, notes, and snippets.

@sooop sooop/client.py Secret
Created Jun 3, 2019

Embed
What would you like to do?
싱글 스레드 소켓 멀티플렉싱을 통한 다중 접속 에코서버(selectors 사용)
import time
import random
import socket
from multiprocessing import Process
def run_client(word, port=5557):
sock = socket.socket()
sock.connect(('localhost', port))
sock.sendall(word.encode())
data = sock.recv(1024)
print(data.decode())
sock.close()
def main():
words = 'apple hello world banana orange shuffle'.split()
for _ in range(10):
Process(target=run_client, args=(random.choices(words))).start()
if __name__ == '__main__':
main()
import selectors
import socket
def accept_handler(sock, mask):
conn, addr = sock.accept()
print(f'accepted: {conn} from {addr}')
conn.setblocking(False)
sel.register(conn, selectors.EVENT_READ, read_handler)
def read_handler(conn, mask):
data = conn.recv(1000)
if data:
print(f'echoing: {repr(data)} to {conn}')
conn.send(data)
else:
print('closing')
sel.unregister(conn)
conn.close()
sel = selectors.DefaultSelector()
sock = socket.socket()
sock.bind(('localhost', 5557))
sock.listen(100)
sock.setblocking(False)
sel.register(sock, selectors.EVENT_READ, accept_handler)
while True:
events = sel.select()
for key, mask in events:
callback = key.data
callback(key.fileobj, mask)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.