def main_server(COMM): nprocs = COMM.Get_size() myrank = COMM.Get_rank() service, port, info = None, None, MPI.INFO_NULL if myrank == 0: port = MPI.Open_port(info) log(COMM, "open port '%s'", port) service = 'cpi' MPI.Publish_name(service, info, port) log(COMM, "service '%s' published.", service) else: port = '' log(COMM, "waiting for client connection ...") icomm = COMM.Accept(port, info, root=0) log(COMM, "client connection accepted.") worker(icomm) log(COMM, "disconnecting from client ...") icomm.Disconnect() log(COMM, "client disconnected.") if myrank == 0: MPI.Unpublish_name(service, info, port) log(COMM, "service '%s' unpublished", port) MPI.Close_port(port) log(COMM, "closed port '%s' ", port)
def close(): MPI.Unpublish_name(self.service, self.info, self.port) print '[Server] Service unpublished' MPI.Close_port(self.port) print '[Server] Service port closed'
def testNamePublishing(self): rank = MPI.COMM_WORLD.Get_rank() service = "mpi4py-%d" % rank port = MPI.Open_port() MPI.Publish_name(service, port) found = MPI.Lookup_name(service) self.assertEqual(port, found) MPI.Unpublish_name(service, port) MPI.Close_port(port)
info = MPI.INFO_NULL port = MPI.Open_port(info) print "Server port: '%s'", port service = 'cpi' MPI.Publish_name(service, info, port) print 'Service %s published', service root = 0 print 'Waiting for connection request' comm = MPI.COMM_WORLD.Accept(port, info, root) print 'Connected to one client' while True: message = comm.recv(source=0, tag=0) if message == 'quit': break else: print 'Receive one message from client:%s' % message comm.Disconnect() print 'Connected with one client' MPI.Unpublish_name(service, info, port) print 'Service unpublished' MPI.Close_port(port) print 'Server port closed'
Run this with 1 processes like: $ mpiexec -n 1 python server.py """ import numpy as np from mpi4py import MPI comm = MPI.COMM_WORLD service_name = 'compute' # open a port port_name = MPI.Open_port() # bind the opened port to a service_name, # client can connect to the port by looking-up this service_name MPI.Publish_name(service_name, port_name) # wait for client to connect inter_comm = comm.Accept(port_name) # receive message from client recv_obj = inter_comm.recv(source=0, tag=0) print 'Server receives %s from client.' % recv_obj send_obj = eval(recv_obj) # reply the result to the client print 'Server sends %s to client.' % send_obj inter_comm.send(send_obj, dest=0, tag=1) # unpublish the service_name, close the port and disconnect MPI.Unpublish_name(service_name, port_name) MPI.Close_port(port_name) inter_comm.Disconnect()