Created
March 28, 2017 08:08
-
-
Save momijiame/bf290519db027d1acb1d59435cfd32cc to your computer and use it in GitHub Desktop.
Eventlet を使って実装したエコーサーバ
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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
# 標準ライブラリにモンキーパッチを当てる | |
# ブロッキング I/O を使った操作が裏側で全てノンブロッキング I/O を使うように書き換えられる | |
import eventlet | |
eventlet.monkey_patch() | |
def client_handler(clientsocket, client_address, client_port): | |
"""クライアントとの接続を処理するハンドラ""" | |
while True: | |
try: | |
message = clientsocket.recv(1024) | |
print('Recv: {0} from {1}:{2}'.format(message, | |
client_address, | |
client_port)) | |
except OSError: | |
break | |
if len(message) == 0: | |
break | |
sent_message = message | |
while True: | |
sent_len = clientsocket.send(sent_message) | |
if sent_len == len(sent_message): | |
break | |
sent_message = sent_message[sent_len:] | |
print('Send: {0} to {1}:{2}'.format(message, | |
client_address, | |
client_port)) | |
clientsocket.close() | |
print('Bye-Bye: {0}:{1}'.format(client_address, client_port)) | |
def main(): | |
host = 'localhost' | |
port = 37564 | |
# Eventlet 経由でサーバソケットを用意する | |
serversocket = eventlet.listen((host, port)) | |
# グリーンスレッドのプールを用意する | |
pool = eventlet.GreenPool() | |
while True: | |
# クライアントからの接続を待ち受ける | |
clientsocket, (client_address, client_port) = serversocket.accept() | |
# 接続がきたらプールのグリーンスレッドで処理する | |
pool.spawn_n(client_handler, clientsocket, client_address, client_port) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment