首页 > 解决方案 > 套接字在第一次接收后停止

问题描述

我有一个 BackGroundWorker 用于在端口中监听
它工作得很好,问题是在第一次接收它停止工作后,我尝试使用“ while(true) ”并在RunWorkerComplete事件中重新启动它但没有成功
使用 stopPoints 我可以看到它使用正确的消息执行 console.writeline(),然后停止工作

    using System.Net.Sockets;

class Program
{

    private static BackgroundWorker worker = new BackgroundWorker();

    static void Main(string[] args)
    {
        Program P = new Program();

        P.notifyIcon1.Visible = true;
        P.ipaddress = IPAddress.Any;
        P.tcpServer = new TcpServer(P.ipaddress.ToString(), 3001);

        worker.DoWork += worker_DoWork;
        worker.RunWorkerCompleted += worker_RunWorkerCompleted;
        //worker.ProgressChanged += worker_ProgressChanged;
        worker.WorkerReportsProgress = true;
        worker.WorkerSupportsCancellation = true;
        if (!worker.IsBusy) worker.RunWorkerAsync();

        Console.WriteLine("Press ENTER to exit the server.");
        Console.ReadLine();
    }


    static void worker_DoWork(object sender, DoWorkEventArgs e)
    {
         IPEndPoint endPoint;
        Socket tcpClient;
        Socket listener;
        int pendingConnectionQueueSize;
        IPAddress ipaddress = IPAddress.Any;

        endPoint = new IPEndPoint(ipaddress, 3001);

        pendingConnectionQueueSize = 100;
        listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        listener.Bind(endPoint);
        listener.Listen(pendingConnectionQueueSize);

        Console.WriteLine("conn..");
        byte[] receiveBuffer = new byte[4096];
        tcpClient = listener.Accept();
        tcpClient.RemoteEndPoint.ToString();

        while (true)
        {
            int rc = tcpClient.Receive(receiveBuffer);
             string msg = Encoding.ASCII.GetString(receiveBuffer);

            if (rc == 0)
                break;

            Console.WriteLine(msg.Trim());
        }

        listener.Close();
    }
    static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (!worker.IsBusy) worker.RunWorkerAsync();//restart

    }

}       

标签: c#tcpclient

解决方案


然后它停止工作

显示的代码有效,并且可以读取尽可能多的数据;我用 telnet 对其进行了测试,它运行良好(ish - 缓冲区的 ASCII 解码仍然存在一些错误,如评论中所述)!

如果它只读取一次,那么我只能假设您的客户端没有在同一连接上发送更多数据。显示的代码只接受一个连接,然后将其读取到最后。


推荐阅读