Question

I'm using the azure emulator. I want to listen on the port 4702 in my worker role. When I have instances count = 1 it doesn't throw the exception. But if to set instances count to 2 then it tries to opent on port 4702 two times (run is fired two times) and exception is thrown: "Only one usage of each socket address (protocol/network address/port) is normally permitted" How to listen for incoming connections in azure's worker role correctly?

the type of the InputEndpoint is "Input" The configuration:

  <WorkerRole name="GpsRerouterWorker" vmsize="Small">
    <Imports>
      <Import moduleName="Diagnostics" />
    </Imports>
    <Endpoints>
      <InputEndpoint name="reroutei4702" protocol="tcp" port="4702" localPort="4702" />
    </Endpoints>
    <LocalResources>
      <LocalStorage name="DiagnosticStore" sizeInMB="20000" cleanOnRoleRecycle="false" />
    </LocalResources>
  </WorkerRole>

the code:

    public class WorkerRole : RoleEntryPoint
    {
        public override void Run()
            {
System.Net.IPEndPoint IPEndpoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["gpsreroutei4702"].IPEndpoint;                TcpListener listener = new TcpListener(IPEndpoint);
                listener.Start();

            Logger.Log("Server is running");

            while (true)
            {
                Logger.Log("Waiting for connections...");
                try
                {
                    var tcpClient = await listener.AcceptTcpClientAsync();
                    await HandleConnectionAsync(tcpClient);
                }
                catch (Exception exp)
                {
                    Logger.Log(exp.ToString());
                }

            }
        }

        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections 
            ServicePointManager.DefaultConnectionLimit = 12;

            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

            return base.OnStart();
        }
    }

UPD: Updated the code. now it works.

Was it helpful?

Solution

I think your problem might be with the IPAddress.Any line. If you spin up multiple instances of the same role in the emulator, each instance should get it's own IPAddress.

The following properties should give you the IP and port for each instance.

RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["reroutei4702"].
IPEndpoint.Address.ToString();

RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["reroutei4702"].
IPEndpoint.Port
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top