472,807 Members | 3,566 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

asyncore asynchat

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 question is asyncore / asynchat. I
have read that twisted makes this all simple, but, I wanted to get my hands
dirty here for educational purposes.

I've managed to build a small echo server with asyncore and asynchat that can
handle any number of connections and repeat to all clients what was sent in
by individual clients. The server seems to work well.

The GUI client, wxPython, creates a socket on open. The user types some text
and clicks [SEND]. The send event puts the text out to the socket then reads
the response and adds it to list control. Everything works well.

I'm now ready for the next step, to disconnect the send data from the recieve
data. So a user who does not send text, still gets what others may have
written. I need to somehow poll the thread so "add to list control" can be
triggered on recieving the data.

I've tried several approaches and can't seem to get it right. First I tried
setting up a separate threading.Thread that created the socket. This way I
could put a poll on the socket. I even created (borrowed) a custom event so
when data was found, it could notify the GUI and call the "add to list
control" But I must have been doing it wrong because it kept locking up in
the loop..

I knew from the server side that asynchat has built in helpers with
collect_incoming_data() and found_terminator(). (my terminator is appended
when data is sent to the server) I could then use the asyncore.poll() in my
threading.Thread to raise the custom event that sends data to the GUI, when
something comes over the socket.

I think I have the concepts right, but the execution breaks down here. I
tried having the threading.Thread create an asyn_chat but I keep getting
errors that I assume the asyncore.dispatcher takes care of. So... maybe I
should use both core and chat on the client as well as the server. The only
examples of dispatcher I can find open up an asyn_chat on "listen". The
client needs to initiate the communication when it starts. The server is
listening and will respond. I won't know on which port the response will
come back.

Here's some bits showing what I'm trying to do. You may find some of it
familiar. I hope I didn't clip anything that may have been needed If anybody
has time to point out where I'm going wrong it would be very helpful. Thank
you if you were patient enough to get this far...

import threading
import time
import socket
import asyncore
import asynchat
from wxPython.wx import *

# server is listening on ...

class MyTest(wxFrame):
def __init__(self, parent, ID, title):
# Initialize wxFrame
wxFrame.__init__(self, .....

# start the thread
self.network = NetworkThread(self)

# build rest of GUI... works fine
# the network thread communicates back to the main
# GUI thread via this sythetic event
class NetworkEvent(wxPyEvent):
def __init__(self,msg=""):
self.msg = msg

wxEVT_NETWORK = 2000
def EVT_NETWORK(win, func):
win.Connect(-1, -1, wxEVT_NETWORK, func)

class NetworkThread(threading.Thread):
def __init__(self,win):
self.win = win
self.keep_going = true
self.running = false
self.MySock = NetworkServer(REMOTE_HOST, REMOTE_PORT,
self.event_loop = EventLoop()

def push(self,msg):
def is_running(self):
return self.running
def stop(self):
self.keep_going = 0
def check_status(self,el,time):
if not self.keep_going:
def received_a_line(self,m):
def run(self):
self.running = true
# loop here checking every 0.5 seconds for shutdowns etc..
# server has shutdown
self.send_event("Closed down network")
self.running = false

# send a synthetic event back to our GUI thread
def send_event(self,m):
evt = NetworkEvent(m)
del evt

class NetworkServer (asyncore.dispatcher):
def __init__ (self, host, port, handler=None):
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect((host, port))

def handle_connect (self):
# I thought, maybe, the server would trigger this... nope
ChatSocket (host, port, self.handler)

def handle_read (self):
data = self.recv (8192)
print data

def writable (self):
return (len(self.buffer) > 0)

def handle_write (self):
sent = self.send (self.buffer)
self.buffer = self.buffer[sent:]

# send a synthetic event back to our GUI thread
def send_event(self,m):
evt = NetworkEvent(m)
del evt

class ChatSocket(asynchat.async_chat):
def __init__(self, host, port, handler=None):
asynchat.async_chat.__init__ (self, port)

def collect_incoming_data(self, data):

def found_terminator(self):
if self.handler:
print 'warning: unhandled message: ', self.data
self.data = ''

class EventLoop:
socket_map = asyncore.socket_map
def __init__ (self):
self.events = {}

def go (self, timeout=5.0):
events = self.events
while self.socket_map:
print 'inner-loop'
now = int(time.time())
for k,v in events.items():
if now >= k:
v (self, now)
del events[k]
asyncore.poll (timeout)

def schedule (self, delta, callback):
now = int (time.time())
self.events[now + delta] = callback

def unschedule (self, callback, all=1):
"unschedule a callback"
for k,v in self.events:
if v is callback:
del self.events[k]
if not all:

# -----------------------------------------
# Run App
# -------------------------------------------
class TestApp(wxApp):
def OnInit(self):
frame = MyTest(None, -1, "Test APP")
return true

app = TestApp(0)
Jul 18 '05 #1
0 2646

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

Similar topics

by: F.G.Testa | last post by:
Hi! Is there a way to access a specific connected socket when using a derived asyncore.dispatcher and derived asynchat.async_chat? class AcmeServer(asyncore.dispatcher): def __init__(self,...
by: David M. Wilson | last post by:
Hi peeps, I finally got around recently to doing something serious using Python for serving network clients asynchronously, deciding on asyncore as my starting point. After 2 days or so of...
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...
by: Jos | last post by:
Hello. I'm using the asyncore and _chat modules to create a network server. I also have, running in a separate thread(s), a "producer" which needs to "push" data onto the network connection(s)....
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...
by: billie | last post by:
Hi all. I've just terminated a server application using asyncore / asynchat frameworks. I wrote a test script that performs a lot of connections to the server app and I discovered that asyncore...
by: Paul Kozik | last post by:
I am working on the networking code for a small Multiplayer RPG I'm working on. I currently have some basic code using threads, but it seems like asyncore would be far better suited for my needs....
by: Giampaolo Rodola' | last post by:
Hi, I post this message here in the hope someone using asyncore could review this. Since the thing I miss mostly in asyncore is a system for calling a function after a certain amount of time, I...
by: Frank Millman | last post by:
Hi all I have been using my own home-brewed client/server technique for a while, using socket and select. It seems to work ok. The server can handle multiple clients. It does this by creating a...
by: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
by: linyimin | last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Sept 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
by: DJRhino | last post by:
Private Sub CboDrawingID_BeforeUpdate(Cancel As Integer) If = 310029923 Or 310030138 Or 310030152 Or 310030346 Or 310030348 Or _ 310030356 Or 310030359 Or 310030362 Or...
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
by: Mushico | last post by:
How to calculate date of retirement from date of birth
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

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.