Skip to content

Instantly share code, notes, and snippets.

@PyYoshi
Created December 20, 2011 07:04
Show Gist options
  • Select an option

  • Save PyYoshi/1500605 to your computer and use it in GitHub Desktop.

Select an option

Save PyYoshi/1500605 to your computer and use it in GitHub Desktop.
asyncoreのテスト クライアントとサーバで1+1の処理を通信します。 async_dis.py→cli.pyの順に起動すること。
# -*- coding:utf-8 -*-
import asyncore
import socket
import os
import sys
addresses = [
('localhost',252525), # dispatcher
]
class PlusOneHandler(asyncore.dispatcher_with_send):
def handle_read(self):
data = self.recv(1024)
if data:
print 'Received -> %s' % (data)
if data == 'start':
data = '1'
else:
data = str(int(data)+1)
self.send(data)
class Server(asyncore.dispatcher):
def __init__(self,address):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind(address)
self.listen(5)
def handle_accept(self):
pair = self.accept()
if pair is None:
pass
else:
sock, addr = pair
print 'Incoming connection from %s' % repr(addr)
handler = PlusOneHandler(sock)
try:
server = Server(addresses[0])
print 'PID: %s' % os.getpid()
print 'Waiting for connections...'
asyncore.loop()
except Exception,e:
server.close()
print e
sys.exit()
# -*- coding:utf-8 -*-
import socket
import os
import sys
addresses = [
('localhost',252525), # dispatcher
]
if __name__ in '__main__':
try:
clisock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
clisock.connect(addresses[0])
print 'PID: %s' % os.getpid()
print 'Waiting for connections...'
# 無限ループ
for count in range(10):
if count == 0:
c_msg = 'start'
clisock.sendall(c_msg)
else:
rcvmsg = clisock.recv(1024)
print 'Received -> %s' % (rcvmsg)
c_msg = str(int(rcvmsg)+1)
clisock.sendall(c_msg)
if rcvmsg == '':
break
count += 1
except Exception,e:
print e
clisock.close()
sys.exit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment