【发布时间】:2021-07-10 05:01:24
【问题描述】:
我的程序很简单,连接到 Socket.IO 服务器,发出一条消息,然后等待一条响应。我怎样才能让它保持运行以接收消息 - 它在连接后立即退出。这是我的第一个 C# 程序,它没有遵循教程,所以它可能有很多错误。
using System;
using System.Windows.Forms;
using System.Threading.Tasks;
using SocketIOClient;
namespace socketio
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Application.Run(new Form1());]
SocketIO client = new SocketIO("http://localhost:5000", new SocketIOOptions
{
EIO = 4
});
Connect();
async Task Connect()
{
client.ConnectAsync();
MessageBox.Show("Started");
client.OnConnected += async (socketSender, b) =>
{
await client.EmitAsync("data", new
{
deviceName = System.Environment.MachineName
});
};
client.On("popup", response =>
{
var obj = response.GetValue(0);
string title = obj.GetProperty("title").GetString();
string message = obj.GetProperty("message").GetString();
MessageBox.Show(message, title);
});
}
}
}
}
【问题讨论】:
-
你必须让它永远做一些事情。如果它是一个控制台程序,那么
Console.ReadLine()在某些情况下可能就足够了,但除非有后台线程,否则它不会真正工作。另请注意,控制台程序中不需要这些视觉样式等,如果有的话。作为 GUI 应用程序执行此操作会更容易,因为它们在默认关闭之前一直保持活动状态。 -
@SamiKuhmonen。我现在已经切换到 WPF - 它看起来更容易一些,并根据stackoverflow.com/a/6691090 制作了一个隐藏窗口。感谢您的提示!
标签: c# socket.io background-process