尝试在 c# 中实现套接字编程,它将以 json 格式传递数据以命中节点 js 服务器

Trying to implement socket programming in c# which will pass the data in json format to hit a node js server

尝试在 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();
                }
            }
        }

    }
}

我看到您使用的 Dispatcher inside a static method. CoreDispatcher.RunAsync 方法不是静态的。所以你不能在静态方法中使用它。将方法更改为非静态将解决您的问题。

如果您想静态调用它,请尝试从静态 CoreApplication.MainView 中访问它,如下所示:

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

 });

详情请看this thread,虽然是针对WPF的,但也可以参考。