【发布时间】:2018-08-29 03:03:43
【问题描述】:
我们有一个 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();
}
}
【问题讨论】:
-
您的意思是您正在运行两个正在侦听同一端口的应用程序?
-
我猜
localAddr不是要绑定的正确地址。将您的 IP 地址更改为IPAddress.Any并重试。 -
如果我更改为 IpAddress.Any,它会抛出异常:“System.Net.Sockets.SocketException: '每个套接字地址(协议/网络地址/端口)通常只允许使用一次'
-
@JonathanHansen 那是因为你一次只能有一个进程绑定到一个端口。
标签: c# tcpclient tcplistener