Winforms服务器套接字应用程序

本文关键字:应用程序 套接字 服务器 Winforms | 更新日期: 2023-09-27 18:11:36

我正在尝试创建一个winforms应用程序,侦听端口10000上的流量,并且基本上作为客户端应用程序和远程数据库的中间人。它应该有一个监听和接受线程,当客户端连接时打开一个单独的客户端线程。然后,这个客户端线程将处理与客户端程序的通信。侦听器应用程序有两个列表框,其中包含正在连接的用户和正在执行的操作的信息。

现在,我正在尝试使用微软在这里给出的示例程序,并根据我的需要对其进行修改,但如果有人有任何建议,我可以在其他地方寻找,我很乐意听到它。

当我试着跌跌撞撞地完成这个过程时,有一件事我还没能弄清楚,那就是如何在不锁定我的电脑的情况下让这个监听器运行起来。下面是我的表单代码(包括一个退出按钮和一个清除列表框的按钮):

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
    }
    private void btnExit_Click(object sender, EventArgs e) {
        this.Close();
    }
    private void btnClearList_Click(object sender, EventArgs e) {
        this.lbActionLog.Items.Clear();
        this.lbUserLog.Items.Clear();
        count = 0;
        this.txtCount.Text = count.ToString();
    }
    private void Form1_Load(object sender, EventArgs e) {
        Server begin = new Server();
        begin.createListener();
    }
}

这里是我的监听器代码,它是用begin。createllistener:

调用的
int servPort = 10000;
        public void createListener() {
            // Create an instance of the TcpListener class.
            TcpListener tcpListener = null;
            IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
            string output = "";
            try {
                // Set the listener on the local IP address and specify the port.
                // 
                tcpListener = new TcpListener(ipAddress, servPort);
                tcpListener.Start();
                output = "Waiting for a connection...";
            }
            catch (Exception e) {
                output = "Error: " + e.ToString();
                MessageBox.Show(output);
            }
            while (true) {
                // Always use a Sleep call in a while(true) loop 
                // to avoid locking up your CPU.
                Thread.Sleep(10);
                // Create socket
                //Socket socket = tcpListener.AcceptSocket(); 
                TcpClient tcpClient = tcpListener.AcceptTcpClient();
                // Read the data stream from the client. 
                byte[] bytes = new byte[256];
                NetworkStream stream = tcpClient.GetStream();
                stream.Read(bytes, 0, bytes.Length);
                SocketHelper helper = new SocketHelper();
                helper.processMsg(tcpClient, stream, bytes);
            }
        }

现在,这只在tcpListener.AcceptSocket上停止。表单永远不会加载,显然列表框没有被填充。如何使这个侦听器在应用程序启动时自动运行,同时仍然加载表单并更新列表框?我希望这个应用程序启动并随时准备接受连接,而不需要有一个已经坐在那里等待。

Winforms服务器套接字应用程序

您正在使用阻塞方法,以便Form1_Load永远不会结束,因为它等待传入的连接。

一个简单的解决方法是启动一个处理连接的新线程:

private void Form1_Load(object sender, EventArgs e) {
    new Thread( 
        () =>
        {
           Server begin = new Server();
           begin.createListener();
        } 
    ).Start();
}