c# - 为什么 TcpListener 不监听?
问题描述
我们有一个 C++ v100 应用程序,它正在处理我们系统中的每个事件,侦听端口 1705,运行主机名。(它非常适合 C++ 应用程序,我们不想更改 C++ 代码中的任何内容)我们试图将其中一些事件截获到 C# 4.5.2 解决方案中,只是为了在我们的新 Web 系统中显示特定事件.
我编写了以下代码,试图监听 1705 端口的流量……但我从未收到任何数据。(我可以创建发送到 1705 的事件)
以下代码运行,并使其变为“等待连接”,但从未变为“已连接!”。如果您在以下代码中看到我无法接收数据的任何原因,请告诉我:
private void PortListener()
{
TcpListener server = null;
try
{
// Set the TcpListener on port 13000.
var port = 1705;
var localAddr = IPAddress.Parse(Dns.GetHostAddresses(Environment.MachineName)[0].ToString());
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
var bytes = new byte[256];
// Enter the listening loop.
while (true)
{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
var client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
// Get a stream object for reading and writing
var stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
var data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
// Process the data sent by the client.
data = data.ToUpper();
//TODO: Process the data
}
// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
server?.Stop();
}
}
解决方案
I'm doing this all wrong. In order to listen to an already opened Port, I need to use a TcpClient to connect and listen. Only a single TcpListener is allowed per port. Several TcpClients can connect at once. Sigh.
推荐阅读
- jakarta-ee - WebLogic 12c:无法初始化 JNDI 上下文
- jenkins - Cucumber 测试竞态条件 Jenkins 在并发服务器上运行
- vb.net - Html 敏捷包无法抓取图像
- jenkins - 如何将 SonarCloud 与 GitHub 和 Jenkins 集成
- typescript - 在 Typescript 中提取静态成员类对象的类型
- google-apps-script - 在 Google 表单上提交时,如何在调试模式下运行 Google App 脚本?
- python - 使用逗号分隔值和红色字体为负值格式化显示在 jupyter 笔记本中的熊猫数据帧
- laravel - 如何与多个结果进行雄辩的关系
- c# - 如何在 Roslyn 推荐的符号中包含关键字和别名?
- javascript - 当我使用 html2canvas 导出甘特仪表板时,为什么我的 PowerPoint 演示文稿是空白的?