Попытка реализовать Программирование сокета в C#, который передаст данные в формате json, чтобы попасть на сервер узла js

Пытается реализовать Программирование сокета в C#, который передаст данные в формате json, чтобы ударить сервер узла js. Но есть проблема
«Имя’ Dispatcher ‘ не существует в текущем контексте. как решить эту проблему .ниже приведен код

using CustomSplash.Managers.SpecialistManager;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.Networking.Connectivity;
using Windows.UI.Core;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace CustomSplash.Extras
{
    public class Utility
    {
        public string Name { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public string Profile { get; set; }
        public string status { get; set; }
        public string date { get; set; }

        public static bool isEmptyString(string str)
        {
            if (str.Equals(string.Empty) || str.Equals(""))
            {
                return true;
            }
            return false;
        }

        public static string getFormatedDate(DateTime dateAndTime)
        {
            string date = dateAndTime.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            Log.print(date);
            return date;

        }

        public async static void showMessageDialog(string message, string title)
        {
            var dialog = new MessageDialog(message, title);
            await dialog.ShowAsync();
        }

        public async static Task<string> getSysFileJsonSendToServer(string studentName, string studentEmail, string studentPhoneNumber, string studentPassw)
        {

        DateTime dateTimeCurrent = await WebServiceManager.GetDateFromServer();
            DateTime localTime = dateTimeCurrent.ToLocalTime();
            string localDateTimeString = Utility.getFormatedDate(localTime);
            string finalJsonObjectToServer = string.Empty;
            try
            {

                Stream serverStream = null;
                string readData = string.Empty;
                string msg = "Conected to Chat Server ...";
                //string concat= {"name":"studentName","phone":"studentPhoneNumber","mail_id":"studentEmail","studentPassw":"hkfgd","profile":"God","status":"1","created_at":"localDateTimeString"}
                var student = new Utility {
                    Name = studentName,
                    Phone = studentPhoneNumber,
                    Email = studentPassw,
                    Profile = "God",
                    status = "1",
                    date = localDateTimeString.ToString()
                };
                string json = JsonConvert.SerializeObject(student);//now in json format
                // Declare member objects
                // Client for tcp, network stream to read bytes in socket
                Windows.Networking.Sockets.StreamSocket tcpClient = new Windows.Networking.Sockets.StreamSocket();

                // Purpose:     Connect to node.js application (lamechat.js)
                // End Result:  node.js app now has a socket open that can send
                //              messages back to this tcp client application

                Windows.Networking.HostName serverHost = new Windows.Networking.HostName("10.2.11.25");
                await tcpClient.ConnectAsync(serverHost, "5000");

                serverStream = tcpClient.OutputStream.AsStreamForWrite();

                //StreamWriter writer = new StreamWriter(serverStream);
                //string request = txtChatName.Text.Trim() + " is joining";
                //await writer.WriteLineAsync(request);
                //await writer.FlushAsync();

                // Purpose:     Send the text in typed by the user (stored in
                //              txtOutMsg)
                // End Result:  Sends text message to node.js (lamechat.js)
                serverStream = tcpClient.OutputStream.AsStreamForWrite();
                StreamWriter writer = new StreamWriter(serverStream);
                string request = json;
                await writer.WriteLineAsync(request);
                await writer.FlushAsync();

                Task taskOpenEndpoint = Task.Factory.StartNew(() =>
                {
                    while (true)
                    {
                        // Read bytes
                        //serverStream = tcpClient.GetStream();
                        serverStream = tcpClient.InputStream.AsStreamForRead();
                        byte[] message = new byte[4096];
                        int bytesRead;
                        bytesRead = 0;

                        try
                        {
                            // Read up to 4096 bytes
                            bytesRead = serverStream.Read(message, 0, 4096);
                        }
                        catch
                        {
                            /*a socket error has occured*/
                        }

                        //We have rad the message.
                        ASCIIEncoding encoder = new ASCIIEncoding();
                        // Update main window
                        AddMessage(encoder.GetString(message, 0, bytesRead));
                        //Thread.Sleep(500);
                        Task.Delay(TimeSpan.FromSeconds(500));

                    }
                });     

           }

            catch (Exception ex)
            {
                Log.print(ex.StackTrace);
            }

            return finalJsonObjectToServer;
        }

        // Purpose:     Updates the window with the newest message received
        // End Result:  Will display the message received to this tcp based client
        private async static void AddMessage(string msg)
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
             () =>
             {
                 this.txtConversation.Text += string.Format(
                          Environment.NewLine + Environment.NewLine +
                          " >> {0}", msg);

             });
        }     



        public async static Task showMessageDialogAndClose(string message, string title)
        {
            var dialog = new MessageDialog(message, title);
            dialog.Commands.Add(new UICommand { Label = "Close", Id = 0 });
            var res = await dialog.ShowAsync();

            if ((int)res.Id == 0)
            {
                CoreApplication.Exit();
            }
        }
        public async static Task showMessageDialogAndBack(string message, string title)
        {
            var dialog = new MessageDialog(message, title);
            dialog.Commands.Add(new UICommand { Label = "Close", Id = 0 });
            var res = await dialog.ShowAsync();

            if ((int)res.Id == 0)
            {
                Frame currentFrame = Window.Current.Content as Frame;
                if (currentFrame.CanGoBack)
                {
                    currentFrame.GoBack();
                }
            }
        }

    }
}

1 ответ

  1. Я видел, что вы использовали Dispatcherвнутри статический метод. CoreDispatcher.RunAsyncметод не статичен. Таким образом, вы не можете использовать его в статическом методе. Изменение метода на нестатический решит вашу проблему.

    Если вы хотите вызвать это статически, пожалуйста, попробуйте получить доступ к нему из статического CoreApplication.MainView как следует:

    await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, 
     () =>
     {         
    
     });
    

    Подробнее см. Этот поток, хотя он предназначен для WPF, но также может ссылаться.