【问题标题】:What is the best place to declare the connection of my socket and my spot in the background?在后台声明我的套接字和我的位置的连接的最佳位置是什么?
【发布时间】:2019-04-24 21:41:58
【问题描述】:

我在UWP下开发了一个HMI,它需要连接服务器和后台任务来监控是否收到消息。

在启动 HMI 时,会出现一个带有进度环的扩展启动屏幕。要取消阻止启动,您必须从服务器接收“launch_ok”,然后我们才能访问允许管理呼叫的主页。

目前我在我的文件中声明所有内容:ExtendedSplash.xaml.cs

我用这些设置声明我的新套接字,我运行它,然后我运行我的后台活动。

我也有一些错误:“Exception levée:'System.NullReferenceException'”

ExtendedSplash.xaml.cs(提取):

namespace PhoneCenter
{
partial class ExtendedSplash : Page
   {
    // SOCKET CONFIGURATION
    private const string socketId = "SampleSocket"; 
        private StreamSocket socket = null;
        private IBackgroundTaskRegistration task = null;
    private const string port = "40404";        
    private const string adress = "172.16.161.80"; 
}
public ExtendedSplash(SplashScreen splashscreen, bool loadState)
   {
        InitializeComponent();
        Window.Current.SizeChanged += new WindowSizeChangedEventHandler(ExtendedSplash_OnResize);
            splash = splashscreen;
    Debug.WriteLine("Création de la tâche d'arrière plan");
            StartBackgroundTask();
        Debug.WriteLine("Connexion Socket ...");
        StartConnexionServeurLTO();

            if (splash != null)
            {
            splash.Dismissed += new TypedEventHandler<SplashScreen, object>(DismissedEventHandler);
            splashImageRect = splash.ImageLocation;
            PositionImage();
            PositionRing();
            PositionTextBlock();
            }
        rootFrame = new Frame();
        RestoreState(loadState);
    }
// CONNEXION SOCKET
    private async void StartConnexionServeurLTO()
    {
        ApplicationData.Current.LocalSettings.Values["hostname"] = adress;
        ApplicationData.Current.LocalSettings.Values["port"] = port;

        try
        {
            SocketActivityInformation socketInformation;
            if (!SocketActivityInformation.AllSockets.TryGetValue(socketId, out socketInformation))
            {
                Debug.WriteLine("Boucle");
                socket = new StreamSocket();
                socket.EnableTransferOwnership(task.TaskId, SocketActivityConnectedStandbyAction.Wake);
                var targetServer = new HostName(adress);
                await socket.ConnectAsync(targetServer, port);
                DataReader reader = new DataReader(socket.InputStream);
                reader.InputStreamOptions = InputStreamOptions.Partial;
                var read = reader.LoadAsync(250);
                read.Completed += (info, status) =>
                {

                };
                await socket.CancelIOAsync();
                socket.TransferOwnership(socketId);
                socket = null;
            }
        }
        catch
        {
            Debug.WriteLine("Echec dans la connexion au serveur");
        }
    }
// LANCEMENT TÂCHE EN ARRIERE PLAN
    private void StartBackgroundTask()
    {
        try
        {
            foreach (var current in BackgroundTaskRegistration.AllTasks)
            {
                if (current.Value.Name == "PhonieMarthaBackground")
                {
                    task = current.Value;
                    break;
                }
            }
            if (task == null)
            {
                var socketTaskBuilder = new BackgroundTaskBuilder();
                socketTaskBuilder.Name = "PhonieMarthaBackground";
                socketTaskBuilder.TaskEntryPoint = "PhonieMarthaBackground.SocketActivityTask";
                var trigger = new SocketActivityTrigger();
                socketTaskBuilder.SetTrigger(trigger);
                task = socketTaskBuilder.Register();
            }

            SocketActivityInformation socketInformation;
            if (SocketActivityInformation.AllSockets.TryGetValue(socketId, out socketInformation))
            {
                socket = socketInformation.StreamSocket;
                socket.TransferOwnership(socketId);
                socket = null;
            }

            Debug.WriteLine("Tâche d'arrière plan démarrée");
        }
        catch (Exception exception)
        {
            Debug.WriteLine(exception.Message);
        }
    }
}

在启动 OnLaunched 时在 App.xaml.cs 文件中执行这些操作不是更简单吗?我们可以在 OnLaunched 结束时调用一个函数吗?

【问题讨论】:

  • 哪一行出现错误?
  • 我不知道...它出现在可视化调试器上,但它没有进入套接字的尝试但捕获
  • 您需要设置一个断点并查看它是如何逐行运行的。
  • socket.TransferOwnership(socketId) 就是这一行
  • 这样的行有两条。是哪个扔的?

标签: c# sockets xaml uwp


【解决方案1】:

您面临的问题是,如果您正在检查是否找不到该值:

if (!SocketActivityInformation.AllSockets.TryGetValue(socketId, out socketInformation))
{
    // Your code
}

如果此值为false,则未找到socketId 的值,因此socketInformation(未初始化)将获得默认值null。这就是问题的原因。如果找到了值,则应更改 if 以输入代码块:

if (!SocketActivityInformation.AllSockets.TryGetValue(socketId, out socketInformation))
{
    // Your code
}

【讨论】:

    猜你喜欢
    • 2021-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2011-09-30
    相关资源
    最近更新 更多