c# - 套接字在第一次接收后停止
问题描述
我有一个 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
}
}
解决方案
然后它停止工作
显示的代码有效,并且可以读取尽可能多的数据;我用 telnet 对其进行了测试,它运行良好(ish - 缓冲区的 ASCII 解码仍然存在一些错误,如评论中所述)!
如果它只读取一次,那么我只能假设您的客户端没有在同一连接上发送更多数据。显示的代码只接受一个连接,然后将其读取到最后。
推荐阅读
- dialog - 应该如何在 GMS3 中部署图形斜角按钮?
- firebase-realtime-database - 如何使用 axios 从我的 firebase 实时数据库请求基本身份验证令牌?
- tuples - OCaml 匹配元组?为什么这个火柴盒不用?
- java - 搜索插入位置好方法
- python - 如何在 python 中发送 XBUTTON1 或 XBUTTON2?
- solr - Solr 突出显示仅在查询以
- python - 启动器中的致命错误:无法使用 pip 创建进程
- html - 为什么此 png 图像出现两次?
- javascript - Javascript 通过从多个图像/按钮获取 onclick 输入来输出图像
- amazon-web-services - 如何在 AWS Glue 作业中从 S3 中逐行读取 CSV 文件