Opening a TCP socket from an Azure Website to an external server

若如初见. 提交于 2019-12-14 02:17:32

问题


Is it possible to open a TCP socket programmatically in C# from an Azure Website to an external server?

I have a need to check if another server is online - as ping cannot be used on Azure I was going to use TCP socket that the external server is configured to accept.

The code I have used locally works perfectly when pinging a public web server, however on Azure it doesn't work.

I'm aware that you can't ping due to the load balancer on Azure - but are opening TCP sockets out of the question too?

Can this be achieved? If not - how else can I check if an external server is alive without using a lengthy work around?

Note: There is definitely no firewall / port / IP issue with the external server.

This is my code that works on my local dev machine and on Rackspace

 public static bool TcpConnectivityTest(string ipAddress, int port = 1433, int timeoutMillisec = 2000)
    {
        Socket socket = null;

        try
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, false);

            var result = socket.BeginConnect(ipAddress, port, null, null);
            result.AsyncWaitHandle.WaitOne(timeoutMillisec, true);

            return socket.Connected;
        }
        catch
        {
            return false;
        }
        finally
        {
            if (null != socket)
            {
                socket.Close();
                socket.Dispose();
            }
        }
    }

来源:https://stackoverflow.com/questions/21925629/opening-a-tcp-socket-from-an-azure-website-to-an-external-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!