我正在使用azure仿真器。我想在我的工作角色中侦听端口4702。当我有实例count = 1时,它不会抛出异常。但是如果要将实例数设置为2,那么它会尝试在端口4702上打开两次(运行被触发两次)并抛出异常:“通常只允许使用每个套接字地址(协议/网络地址/端口)” 如何正确地监听azure的worker角色中的传入连接?
InputEndpoint的类型是“输入” 配置:
<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>
代码:
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:更新了代码。现在它有效。
答案 0 :(得分:1)
我认为您的问题可能出在IPAddress.Any
行。如果在模拟器中启动同一角色的多个实例,则每个实例都应该获得它自己的IPAddress。
以下属性应为您提供每个实例的IP和端口。
RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["reroutei4702"].
IPEndpoint.Address.ToString();
RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["reroutei4702"].
IPEndpoint.Port