473,385 Members | 2,044 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,385 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 ...
REMOTE_HOST = '172.0.0.1'
REMOTE_PORT = 50001

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

# start the thread
self.network = NetworkThread(self)
self.network.start()
EVT_NETWORK(self,self.OnNetwork)

# 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=""):
wxPyEvent.__init__(self)
self.SetEventType(wxEVT_NETWORK)
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):
threading.Thread.__init__(self)
self.win = win
self.keep_going = true
self.running = false
self.MySock = NetworkServer(REMOTE_HOST, REMOTE_PORT,
self.received_a_line)
self.event_loop = EventLoop()

def push(self,msg):
self.MySock.push(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:
asyncore.close_all()
else:
self.event_loop.schedule(1,self.check_status)
def received_a_line(self,m):
self.send_event(m)
def run(self):
self.running = true
self.event_loop.schedule(1,self.check_status)
# loop here checking every 0.5 seconds for shutdowns etc..
self.event_loop.go(0.5)
# server has shutdown
self.send_event("Closed down network")
time.sleep(1)
self.running = false

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

class NetworkServer (asyncore.dispatcher):
def __init__ (self, host, port, handler=None):
asyncore.dispatcher.__init__(self)
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)
self.send_event(self.data)
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)
wxPostEvent(self.win,evt)
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):
self.data.append(data)

def found_terminator(self):
if self.handler:
self.send_event(self.data)
else:
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:
break

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

app = TestApp(0)
app.MainLoop()
Jul 18 '05 #1
0 2685

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

Similar topics

4
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,...
5
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...
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...
3
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)....
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...
7
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...
7
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....
0
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...
8
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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: 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
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

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.