473,386 Members | 1,652 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

why asynchat's initiate_send() get called twice after reconnect ?

Python3.0rc1 windowsxp

in the lib\asynchat.py

def handle_write (self):
self.initiate_send()

def push (self, data):
sabs = self.ac_out_buffer_size
if len(data) sabs:
for i in range(0, len(data), sabs):
self.producer_fifo.append(data[i:i+sabs])
else:
self.producer_fifo.append(data)
self.initiate_send()

when there's only one time connection, the object works just fine. but
problems came out when the client disconnected and reconnected again
to the server, it seems there are two ways to call the initiate_send,
one is from push() which I called in my program, one is from
handle_write() which automatically called in asyncore.loop(). I just
can't get it why one time connection works fine but multi-time
connection went bad.

I printed the traceback. I found when one time connection made, the
handle_write() always get silent, but when the second time, it get
called and start to call initiate_send in the same time as push() get
called. So confusing....

So I tried to remove the initiate_send from push() and the code
magically works fine for me.

the main program lists below:
since it's need a flash client, I attached a webpage to reproduce the problem
click on the connect button multiple times and clicked on the send
button will make an error

import asyncore, asynchat
import os, socket, string
from multiprocessing import Process,Manager
import pickle
import _thread
import threading

PORT = 80

policyRequest = b"<policy-file-request/>"
policyReturn = b"""<cross-domain-policy>
<allow-access-from domain="*" to-ports="*" />
</cross-domain-policy\x00"""

def handler(taskList,msgList):
while 1:
print('getting task')
item = pickle.loads(taskList.get())
print('item before handle ', item)
#do something
item['msg'] += b' hanlded done'
msgList.put(pickle.dumps(item))

def findClient(id):
for item in clients:
if item.idx == id:
return item

def pushData(ch,data):
global pushLock
pushLock.acquire()
try:
ch.push(data)
finally:
pushLock.release()
def sender():
global msgList
print('thread started')
while 1:
item = pickle.loads(msgList.get())
#print time()
c = findClient(item['cid'])
#print time()
#wrong here it's not thread safe, need some wrapper
#c.push(item['msg'])
pushData(c,item['msg'])
print('msg sent ',item['msg'])
#print time()

class HTTPChannel(asynchat.async_chat):

def __init__(self, server, sock, addr):
global cid;
asynchat.async_chat.__init__(self, sock)
self.set_terminator(b"\x00")
self.data = b""
cid += 1
self.idx = cid
if not self in clients:
print('add to clients:',self)
clients.append(self)

def collect_incoming_data(self, data):
self.data = self.data + data
print(data)

def found_terminator(self):
global taskList
print("found",self.data)
if self.data == policyRequest:
pushData(self,policyReturn)
self.close_when_done()
else:
d = {'cid':self.idx,'msg':self.data}
taskList.put(pickle.dumps(d))
self.data = b""

def handle_close(self):
if self in clients:
print('remove from clients:',self)
clients.remove(self)

class HTTPServer(asyncore.dispatcher):

def __init__(self, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.bind(("", port))
self.listen(5)

def handle_accept(self):
conn, addr = self.accept()
print('a new customer!')
HTTPChannel(self, conn, addr)
#
# try it out
if __name__ == "__main__":
s = HTTPServer(PORT)
print ("serving at port", PORT, "...")

#push data lock
pushLock = threading.Lock()
clients=[]

cid = 0

manager = Manager()

taskList = manager.Queue()

msgList = manager.Queue()
h = Process(target=handler,args=(taskList,msgList))
h.start()
_thread.start_new_thread(sender,())
print('entering loop')
asyncore.loop()
Oct 25 '08 #1
0 1120

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Michael Welsh | last post by:
In order to learn sockets in Python I am trying to write a simple group chat server and client. I need a little nudge, please. My question contains some GUI but only as decoration. The root...
1
by: Patrick Useldinger | last post by:
I am trying to write both a server and a client using asynchat. For both, I have created a common subclass to collect the incoming data: class SingleServer(asynchat.async_chat): def...
4
by: Joshua Moore-Oliva | last post by:
Ok.. so here is my situation. I have an application that I would love to be able to use asynchat with for it's handle_close, found_terminator etc abstraction on. However, I must use a separate...
1
by: Andreas R. | last post by:
Hello, I'm using Python's asynchat module for network support in a Python-based game, and I run into two problems, both of which occur at random times. Most of the time, the network sending and...
0
by: Z. Kotzer | last post by:
I can not get error notifications when an asynchat based client tries to connect to a non-responsive address. To validate the problem I changed lib/test/test_asynchat.py as follows: class...
0
by: David Hirschfield | last post by:
I'm implementing a relatively simple inter-application communication system that uses asyncore/asynchat to send messages back and forth. The messages are prefixed by a length value and terminator...
1
by: Martin Maney | last post by:
Simple asyncore application where I wanted to use an explicit map (1) rather than the automagic default. Worked fine until I tried to use asynchat to handle an interactive status and control...
5
by: ludvig.ericson | last post by:
Hello, My question concerns asynchat in particular. With the following half- pseudo code in mind: class Example(asynchat.async_chat): def readable(self): if foo:...
0
by: Orestis Markou | last post by:
Hello, I'm trying to add some better error handling to an async_chat client. What I want is to retry or terminate gracefully if the connection to the server doesn't succeed. Here's what I have:...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.