Bryan, Thanks for your note. Finally, I have made "one listener socket for all the connections" work plus Queue-communication between the threads in wxpython Gui and the threads for socket connections. Trying to make that twisted example code in this topic for "one listener socket-all the connections" but failed. That twisted example only accepts one client connection. I have printed out the Twisted help file (256 pages). Too much to read.
Ouyang Bryan Olson 写道: > zxo102 wrote: > > I am doing a small project using socket server and thread in python. > > This is first time for me to use socket and thread things. > > Here is my case. I have 20 socket clients. Each client send a set > > of sensor data per second to a socket server. The socket server will > > do two things: 1. write data into a file via bsddb; 2. forward the data > > to a GUI written in wxpython. > > I am thinking the code should work as follow (not sure it is > > feasible) > > 20 threads, each thread takes care of a socket server with a > > different port. > > I want all socket servers start up and wait for client connection. > > In the attached demo code, It stops at the startup of first socket > > server somewhere in the following two lines and waits for client call: > > > > lstn.listen(5) > > (clnt,ap) = lstn.accept() > > It will block there, waiting for connection. > > > Any ideas how to handle these 20 clients? Really appreciate your > > suggestions. > > One reserved port for each client strikes me as whacked, > as does coding a server to handle exactly 20 of them. Since > you say this is your first socket server, maybe you just > haven't seen the usual techniques. > > Normally, one listener socket accepts all the connections. > Each call to accept() returns a new, independent socket for the > connection. You can then start a thread to handle the new > socket. Untested: > > > listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > listener.bind(('', 2000)) > listener.listen(5) > while True: # or some should_continue() thing > sock, _ = listener.accept() > thread.start_new_thread(service_function, (sock,)) > # Or start threads via class Threading > > > To update the GUI, you could use the Queue from the Python > library, and call wxPostEvent to tell the GUI go wake up and > check the queue. > > > -- > --Bryan -- http://mail.python.org/mailman/listinfo/python-list