如何将此值与c#中的全局变量对齐?

时间:2017-09-22 19:12:21

标签: c# .net

我需要将从套接字(TCP / IP)接收的值设置为变量,因此我可以在表单中的标签中使用它。 我在这里问,因为我一直在寻找和尝试几个小时而且找不到任何东西。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;

namespace ConsoleApp1
{
class Exemys
{
        static byte[] Buffer { get; set; }
        static Socket sck;
        [STAThread]
        public static void Conectar(/*string[] args*/)
        {
            sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint localEndpoint = new IPEndPoint(IPAddress.Parse("192.168.34.230"), 5202);
            try
            {
                sck.Connect(localEndpoint);
                Console.WriteLine("Exemys connected!\r\n");
            }
            catch
            {
                Console.Write("Unable to connect to Exemys\r\n");
                Conectar(/*args*/);
            }
        while (true)
        {
            Buffer = new byte[sck.SendBufferSize];
            int bytesRead = sck.Receive(Buffer);
            byte[] formatted = new byte[bytesRead];
            for (int i = 0; i < bytesRead; i++)
            {
                formatted[i] = Buffer[i];
            }
            string mensaje = Encoding.ASCII.GetString(formatted);
            Console.Write(mensaje + "\r\n");

        }
    }       
}
}

此代码是在类中编写的,而Form位于其他位置。 我需要签名的值是mensaje,所以我可以在表格的文本框中看到它。 对不起我的英文,谢谢!

1 个答案:

答案 0 :(得分:0)

首先,全局变量闻起来像一个糟糕的设计。无论如何,您似乎提供了一个 ConsoleApplication 的示例,但您可能有一个 Windows窗体应用程序?显然,您无法从控制台应用程序运行表单,因此只需将所有内容转换为Windows窗体应用程序即可。

无论如何,在你有一个表格工作后,你可能会改变你的代码,以便 Conectar(),我们实际上我们可以给出一个更好的名称,如 ConnectAndGetMessage()< / strong>,实际返回消息。然后从表单中调用该方法,也可以在Load处理程序中调用。

简而言之,你可以这样做:

class Exemys {

    public static string ConnectAndGetMessage() {
        // Here your code! ;)
        return mensaje;
    }
}

class FormWithTextbox {

    private void FormWithLabel_Load(object sender, System.EventArgs e)
    {
        Textbox1.Text = Exemys.ConnectAndGetMessage();
    }
}

请注意,这不是最佳解决方案,因为无论如何,您应该将Exemys作为依赖项注入,以便以后进行改进。

有关你的代码的另一点需要指出,但是你可能很快就会知道你没有退出while循环,所以你可能最终会陷入无限循环。