具有套接字连接的后台运行服务器

本文关键字:后台 运行 服务器 连接 套接字 | 更新日期: 2023-09-27 18:30:39

现在我有这个:

[STAThread]
static void Main()
        {
            if (flag) //client view
                Application.Run(new Main_Menu());
            else
            {
                Application.Run(new ServerForm());
            }
        }

服务器表单.cs

 public partial class ServerForm : Form
    {
        public ServerForm()
        {
            InitializeComponent();
            BeginListening(logBox);
        }
        public void addLog(string msg)
        {
            this.logBox.Items.Add(msg);
        }
        private void button1_Click(object sender, EventArgs e)
        {
        }
        private async void BeginListening(ListBox lv)
        {
            Server s = new Server(lv);
            s.Start();
        }
    }

服务器.cs

public class Server
    {
        ManualResetEvent allDone = new ManualResetEvent(false);
        ListBox logs;
        ///
        /// 
        /// Starts a server that listens to connections
        ///
        public Server(ListBox lb)
        {
            logs = lb;
        }
        public void Start()
        {
            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            listener.Bind(new IPEndPoint(IPAddress.Loopback, 1440));
            while (true)
            {
                Console.Out.WriteLine("Waiting for connection...");
                allDone.Reset();
                listener.Listen(100);
                listener.BeginAccept(Accept, listener);
                allDone.WaitOne(); //halts this thread
            }
        }
        //other methods like Send, Receive etc.
}

我想运行我的ServerForm(它有列表框从Server打印消息)。我知道ListBox论点是行不通的,但是如果没有挂起ServerForm,我就无法运行Server无限循环(我什至无法移动窗口)。我也尝试过使用线程 - 不幸的是它不起作用。

具有套接字连接的后台运行服务器

WinForms有一个叫做UI线程的东西。它是一个负责绘制和处理 UI 的线程。如果该线程正忙于执行某些操作,则 UI 将停止响应。

常规套接字方法正在阻塞。这意味着它们不会将控制权返回给应用程序,除非套接字上发生了某些事情。因此,每次在 UI 线程上执行套接字操作时,UI 将停止响应,直到套接字方法完成。

要解决这个问题,您需要为套接字操作创建一个单独的线程。

public class Server
{
    ManualResetEvent allDone = new ManualResetEvent(false);
    Thread _socketThread;
    ListBox logs;
    public Server(ListBox lb)
    {
        logs = lb;
    }
    public void Start()
    {
        _socketThread = new Thread(SocketThreadFunc);
        _socketThread.Start();
    }
    public void SocketThreadFunc(object state)
    {
        Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        listener.Bind(new IPEndPoint(IPAddress.Loopback, 1440));
        while (true)
        {
            Console.Out.WriteLine("Waiting for connection...");
            allDone.Reset();
            listener.Listen(100);
            listener.BeginAccept(Accept, listener);
            allDone.WaitOne(); //halts this thread
        }
    }
    //other methods like Send, Receive etc.
}

但是,所有 UI 操作都必须在 UI 线程上进行。如果您尝试从套接字线程更新listbox,则会出现异常。

解决此问题的最简单方法是使用 Invoke。