473,587 Members | 2,526 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

start a multi-sockets server (a socket/per thread) with different ports but same host

Hi,
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()

Any ideas how to handle these 20 clients? Really appreciate your
suggestions.

Thanks a lot.

Ouyang
import socket
import sys
import threading
class srvr(threading. Thread):
v = ''
vlock = threading.Lock( )
id = 0 # next available thread number
def __init__(self,c lntsock):
threading.Threa d.__init__(self )
self.myid = srvr.id
srvr.id += 1
self.myclntsock = clntsock
def run(self):
while 1:
k = self.myclntsock .recv(1)
if k == '': break
# update v in an atomic manner
srvr.vlock.acqu ire()
srvr.v += k
srvr.vlock.rele ase()
self.myclntsock .send(srvr.v)
self.myclntsock .close()

#lstn = socket.socket(s ocket.AF_INET, socket.SOCK_STR EAM)
#port = int(sys.argv[1]) # server port number
#lstn.bind(('', port))
#lstn.listen(5)
nclnt = 20
mythreads = [] # list of all the threads

for i in range(nclnt):
lstn = socket.socket(s ocket.AF_INET, socket.SOCK_STR EAM)
lstn.setsockopt (socket.SOL_SOC KET, socket.SO_REUSE ADDR, 1)
lstn.bind(('', 2000+i+1))
lstn.listen(5)
(clnt,ap) = lstn.accept()
s = srvr(clnt)
mythreads.appen d(s)
s.start()

# shut down the server socket, since it's not needed anymore
#lstn.close()

# wait for all threads to finish
for s in mythreads:
s.join()

print 'the final value of v is', srvr.v

Aug 12 '06 #1
5 4753
Jean-Paul,
Thanks a lot. The code is working. The python twisted is new to me too.
Here are my three more questions:
1. Since the code need to be started in a wxpyhon GUI (either by
clicking a button or up with the GUI), do I have to run the code in a
thread (sorry, I have not tried it yet)?
2. How can I grab the client data in the code? Can you write two lines
for that? I really appreciate that.
3. After I change
self.transport. write(''.join(s elf.data))
to
self.transport. write(''.join(d ata))
and scan all the ports with the following code twice (run twice).
First round scanning says "succefully connected". But second round
scanning says "failed". I have to restart your demo code to make it
work.

Ouyang
import sys, threading, socket

class scanner(threadi ng.Thread):
tlist = [] # list of all current scanner threads
maxthreads = int(sys.argv[2]) # max number of threads we're
allowing
evnt = threading.Event () # event to signal OK to create more
threads
lck = threading.Lock( ) # lock to guard tlist
def __init__(self,t n,host):
threading.Threa d.__init__(self )
#self.threadnum = tn # thread ID/port number
self.threadnum = 2000+tn # thread ID/port number
self.host = host # checking ports on this host
def run(self):
s = socket.socket(s ocket.AF_INET,s ocket.SOCK_STRE AM)
try:
s.connect((self .host, self.threadnum) )
print "%d: successfully connected" % self.threadnum
s.close()
except:
print "%d: connection failed" % self.threadnum
# thread is about to exit; remove from list, and signal OK if we
# had been up against the limit
scanner.lck.acq uire()
scanner.tlist.r emove(self)
print "%d: now active --" % self.threadnum, scanner.tlist
if len(scanner.tli st) == scanner.maxthre ads-1:
scanner.evnt.se t()
scanner.evnt.cl ear()
scanner.lck.rel ease()
def newthread(pn,hs t):
scanner.lck.acq uire()
sc = scanner(pn,hst)
scanner.tlist.a ppend(sc)
scanner.lck.rel ease()
sc.start()
print "%d: starting check" % pn
print "%d: now active --" % pn, scanner.tlist
newthread = staticmethod(ne wthread)

def main():
host = sys.argv[1]
#for i in range(1,100):
for i in range(20):
scanner.lck.acq uire()
print "%d: attempting check" % i
# check to see if we're at the limit before starting a new thread
if len(scanner.tli st) >= scanner.maxthre ads:
# too bad, need to wait until not at thread limit
print "%d: need to wait" % i
scanner.lck.rel ease()
scanner.evnt.wa it()
else:
scanner.lck.rel ease()
scanner.newthre ad(i,host)
for sc in scanner.tlist:
sc.join()

if __name__ == '__main__':
main()


Jean-Paul Calderone 写道:
On 12 Aug 2006 09:00:02 -0700, zxo102 <zx****@gmail.c omwrote:
Hi,
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:

Threads aren't the best way to manage the concurrency present in this
application. Instead, consider using non-blocking sockets with an
event notification system. For example, using Twisted, your program
might look something like this:

from twisted.interne t import reactor, protocol, defer

class CumulativeEchoP rotocol(protoco l.Protocol):
def connectionMade( self):
# Stop listening on the port which accepted this connection
self.factory.po rt.stopListenin g()

# Set up a list in which to collect the bytes which we receive
self.received = []
def connectionLost( self, reason):
# Notify the main program that this connection has been lost, so
# that it can exit the process when there are no more connections.
self.factory.on ConnectionLost. callback(self)

def dataReceived(se lf, data):
# Accumulate the new data in our list
self.received.a ppend(data)
# And then echo the entire list so far back to the client
self.transport. write(''.join(s elf.data))

def allConnectionsL ost():
# When all connections have been dropped, stop the reactor so the
# process can exit.
reactor.stop()

def main():
# Set up a list to collect Deferreds in. When all of these Deferreds
# have had callback() invoked on them, the reactor will be stopped.
completionDefer reds = []
for i in xrange(20):
# Make a new factory for this port
f = protocol.Server Factory()

# Make a Deferred for this port's connection-lost event and make
# it available to the protocol by way of the factory.
d = defer.Deferred( )
f.onConnectionL ost = d
completionDefer reds.append(d)
f.protocol = CumulativeEchoP rotocol

# Start listening on a particular port number with this factory
port = reactor.listenT CP(2000 + i + 1, f)

# Make the port object available to the protocol as well, so that
# it can be shut down when a connection is made.
f.port = port

# Create a Deferred which will only be called back when all the other
# Deferreds in this list have been called back.
d = defer.DeferredL ist(completionD eferreds)

# And tell it to stop the reactor when it fires
d.addCallback(l ambda result: allConnectionsL ost())

# Start the reactor so things can start happening
reactor.run()

if __name__ == '__main__':
main()

Hope this helps,

Jean-Paul
Aug 12 '06 #2
Jean-Paul,
I just start to learn Twisted. Here is my simple case: I can find
the data sent by clients in dataReceived but I don't know which
client/which port the data is from. After I know where the data comes
from, I can do different things there, for example, write them into
different files via bsddb. I am not sure if it is the correct way to
do it.
def dataReceived(se lf, data):
# Accumulate the new data in our list
self.received.a ppend(data)
# And then echo the entire list so far back to the client
self.transport. write(''.join(d ata))

print "============da ta: ", data
print " which Port? : ", self.factory.po rt # unforunately it is
an object here.

# if Port == 2001:
# write the data into a file via bsddb
# if Port == 2002:
# write the data into another file via bsddb
# etc .....
Ouyang

Jean-Paul Calderone 写道:
On 12 Aug 2006 10:44:29 -0700, zxo102 <zx****@gmail.c omwrote:
Jean-Paul,
Thanks a lot. The code is working. The python twisted is new to me too.
Here are my three more questions:
1. Since the code need to be started in a wxpyhon GUI (either by
clicking a button or up with the GUI), do I have to run the code in a
thread (sorry, I have not tried it yet)?

You can try to use Twisted's wxPython integration support:

http://twistedmatrix.com/projects/co...or.html#auto15

But note the warnings about how well it is likely to work. Using a separate
thread might be the best solution.
2. How can I grab the client data in the code? Can you write two lines
for that? I really appreciate that.

I'm not sure what you mean. The data is available in the `received' attribute
of the protocol instance. Any code which needs to manipulate the data can get
that list and do whatever it likes with it.
3. After I change
self.transport. write(''.join(s elf.data))
to
self.transport. write(''.join(d ata))
and scan all the ports with the following code twice (run twice).
First round scanning says "succefully connected". But second round
scanning says "failed". I have to restart your demo code to make it
work.

I intentionally added code which shuts the server off after the first round
of connections is completed, since that seemed to be what your example
program was doing. If you don't want this, just remove the shutdown code.

Jean-Paul
Aug 13 '06 #3
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(s ocket.AF_INET, socket.SOCK_STR EAM)
listener.bind(( '', 2000))
listener.listen (5)
while True: # or some should_continue () thing
sock, _ = listener.accept ()
thread.start_ne w_thread(servic e_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
Aug 13 '06 #4
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(s ocket.AF_INET, socket.SOCK_STR EAM)
listener.bind(( '', 2000))
listener.listen (5)
while True: # or some should_continue () thing
sock, _ = listener.accept ()
thread.start_ne w_thread(servic e_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
Aug 15 '06 #5
"That twisted example only accepts one client connection" if only one
port is available.
zxo102 写道:
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(s ocket.AF_INET, socket.SOCK_STR EAM)
listener.bind(( '', 2000))
listener.listen (5)
while True: # or some should_continue () thing
sock, _ = listener.accept ()
thread.start_ne w_thread(servic e_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
Aug 15 '06 #6

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

Similar topics

21
15683
by: Alexander N. Spitzer | last post by:
If I have a machine with 3 virtual IP addresses (192.168.1.), how can I start 3 instances of the same RMI application (each started with different properties/configs), each listening on the port 1234, but each instance binds to a different ip address. that is to say: instance #1 binds to 192.168.1.5/port 1234 instance #2 binds to 192.168.1.6/port 1234 instance #3 binds to 192.168.1.7/port 1234
8
9272
by: simon place | last post by:
Spent some very frustrating hours recoding to find a way of closing a server socket, i'd not thought it would be any problem, however, after complete failure and as a last resort, i looked at the python wrapper module for sockets, and found that the close command doesn't actually call the underlying close! this didn't seem right, so i added it, and my code now works simply and as expected. def close(self):
4
9421
by: jas | last post by:
I have a basic client/server socket situation setup....where the server accepts a connection and then waits for commands. On the client side, I create a socket, connect to the server...then I pass the socket to a class which just reads from the socket (in a thread). class Reader(Thread): def run(self): while 1:
2
10098
by: giangiammy | last post by:
hi all, I'd like to implement a server socket in java: something linke the following example. The problem is that the HTML has not the permission to execute instruction serverSocket = Components.classes. createInstance(Components.interfaces.nsIServerSocket);
3
2481
by: O.B. | last post by:
When sharing a Socket between threads, are the socket operations automatically synchronized to support multithreading? For example: Thread1 sets up a server socket to listen and invokes BeginAccept. A connection is made and Thread2 (within the BeginAccept delegate) begins. Does the server socket been to be "locked" before Thread2 calls
0
2209
by: Leo Jay | last post by:
I'd like to read and write the same socket in different threads. one thread is only used to read from the socket, and the other is only used to write to the socket. But I always get a 10022 'Invalid argument' exception. Anyone knows why? I'm using windows xp. my source code is here: http://pastebin.com/m23e633a2
0
2945
by: Jean-Paul Calderone | last post by:
On Sat, 23 Aug 2008 02:25:17 +0800, Leo Jay <python.leojay@gmail.comwrote: No - it's just what I said. create_socket creates one socket and passes it to read_socket and write_socket. read_socket calls connect on the socket it is passed. write_socket calls accept on the socket it is passed. So a single socket has connect and accept called on it. Now, main does call create_socket twice, so this does happen to two sockets, but it's...
0
2638
by: ryaneoghan | last post by:
hi, I was just wondering if anyone could help, i am trying to create a client and server socket connection in perl, i want to ask for name and then do a check on the name and ask for a secret word if it does not match, i have this much done but dont know where to go from here and cant find anything to help on net, if you could help using the code i have done i would be grateful, thanks! here is the 2 files #!/usr/bin/perl -w #...
0
1253
by: lucy149 | last post by:
hello , i am trying to implement ftp protoco using javal. but when i read the protocol description ,i didnt get how i should have 2 ports does that mean having 2 server sockets , each one with different port or having only 1 server socket but 2 sockets for the client one for example is called connection socket and the other data socket but if so , does that mean that i can not use the connection socket for any data transfer even if it...
0
7854
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8349
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7978
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6629
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5722
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5395
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3845
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
1455
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1192
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.