gpt4 book ai didi

c# - 套接字在第一次接收后停止

转载 作者:行者123 更新时间:2023-12-04 10:34:19 25 4
gpt4 key购买 nike

我有一个 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

}

}

最佳答案

then it stops working



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

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

关于c# - 套接字在第一次接收后停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60261574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com