0

我正在尝试在现有的 Windows 窗体应用程序中实现简单的 TCP/IP 通信。构成通信部分的代码有一个无限的while循环,我相信它会让服务器不断地监听客户端。它适用于我的应用程序,除了我对如何让它在单独的线程上运行有点卡住。我将在下面发布我的代码:

private TcpListener tcpListener;
    private Thread listenThread;

 private void Form1_Load(object sender, EventArgs e)
    {

        startServer();

    }

private void startServer()
    {
        TcpListener serverSocket = new TcpListener(IPAddress.Parse("127.0.0.1"), 8888);
        TcpClient clientSocket = default(TcpClient);
        serverSocket.Start();

        clientSocket = serverSocket.AcceptTcpClient();

        while ((true))
        {
            try
            {

                NetworkStream networkStream = clientSocket.GetStream();
                byte[] bytesFrom = new byte[10025];
                networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
                string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
                listBox1.Items.Add(" >> Data from client - " + dataFromClient);
                string serverResponse = "Server acknowledges the request - " + dataFromClient;
                Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
                networkStream.Write(sendBytes, 0, sendBytes.Length);
                networkStream.Flush();
                listBox1.Items.Add(" >> " + serverResponse);


            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }



        }
    }

我将不胜感激有关此问题的任何建议。谢谢!

4

1 回答 1

0

使用 BackgroundWorker 并在“DoWork”方法中调用您的服务器,如下所示:

using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
    public Form1()
    {
        InitializeComponent();
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        startServer() // Call here what you want to execute in another thread
    }
    }

}

你可以在这里看到更详细的

于 2012-07-23T19:19:29.590 回答