在后台声明我的套接字和我的位置的连接的最佳位置是什么?

时间:2019-04-24 12:40:29

标签: c# sockets xaml uwp

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

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

当前,我在文件中声明了所有内容:ExtendedSplash.xaml.cs

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

我也有一些错误:“异常级别:'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的末尾调用一个函数吗?

1 个答案:

答案 0 :(得分:0)

您面临的问题是,如果要检查是否未找到该值,则该问题:

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

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

null