我需要将从套接字(TCP/IP)接收的值赋给变量,以便我可以在表单中的标签中使用它。 我在这里问,因为我一直在寻找并尝试几个小时,找不到任何东西。如何将此值赋给c#中的全局变量?
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
,所以我可以在窗体的文本框中看到它。 对不起,我的英语,谢谢!
'“表格在其他地方”' - 还有什么地方?这段代码如何与表单相关? – David
@大卫抱歉,如果我表达自己很差,表单是在同一个项目。我的意思是这个代码不在Form的代码中。 – Joaco
此代码暗示这是控制台应用程序的整体。是吗?表格与此有关? – David