3次成功调用后,Web服务调用导致WSAStartUp错误

时间:2014-10-14 15:54:59

标签: c# webservice-client wsastartup

我有一个C#winforms应用程序,它通过.DLL充当某些访问设备的服务器。

通过向web服务(设置为webreference)发送输入并将结果返回给设备来确定用户访问,但是如果超时,应用程序将断开所有设备的连接,停止服务器并启动BackgroundWorker的。 backgroundworker重试与webservice的连接,如果成功,则再次启动服务器,并重新连接设备。

这一切都运行良好,但不幸的是,在第三或第五次,后台工作者尝试重新连接到webservice,连接失败,异常"应用程序没有调用WSAStartup,或WSAStartup失败" 。每次尝试后,都会出现类似错误。

以下是backgroundworker的源代码,它的代码非常简单:

private void backgroundWorkerStopServer_DoWork(object sender, DoWorkEventArgs e)
    {
        System.Threading.Thread.Sleep(2000);
        stopServer();

        NewDoorCheck.Doorcheck ndoorcheck = new NewDoorCheck.Doorcheck();
        ndoorcheck.Timeout = 15000;

        bool disconnected = true;

        while (disconnected)
        {
            try
            {

                ndoorcheck.WebserviceIsUp();

                UpdateLog("Connected web");
                disconnected = false;
                startServer();
            }
            catch (Exception ex)
            {

                UpdateLog(ex.Message);
                UpdateLog(ex.StackTrace);
                UpdateLog("Still Down");
                System.Threading.Thread.Sleep(60000);
            }
        }

作为旁注,网络服务就像一个魅力。

1 个答案:

答案 0 :(得分:0)

我最终通过在异常处理程序中手动调用WSAstartup并重试来解决此问题。

导入Winsock

class WSAinterop
{
    [StructLayout(LayoutKind.Sequential)]
    internal struct WSAData
    {
        public short wVersion;
        public short wHighVersion;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 257)]
        public string szDescription;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 129)]
        public string szSystemStatus;
        public short iMaxSockets;
        public short iMaxUdpDg;
        public int lpVendorInfo;
    }


    [DllImport("wsock32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
    internal static extern int WSAStartup(
          [In] short wVersionRequested,
          [Out] out WSAData lpWSAData
          );

    [DllImport("wsock32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
    internal static extern int WSACleanup();

    private const int IP_SUCCESS = 0;
    private const short VERSION = 2;
    public static bool SocketInitialize()
    {
        WSAData d;

        return WSAStartup(VERSION, out d) == IP_SUCCESS;
    }

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
}

只需使用SocketInitialize()方法。

bool startup = WSAinterop.SocketInitialize();