You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Netcat监听器可接收JS客户端数据,自制C#监听器收而不显示?

问题分析

你的问题核心在于换行符格式不匹配,同时C#代码存在冗余逻辑:

  1. StreamReader.ReadLine()的触发条件是读取到\n或\r\n,但你的JS客户端仅发送了\r(回车符),导致ReadLine一直阻塞,无法返回内容。
  2. C#代码嵌套了两层无意义的while(true),内层循环在inputLine为null时仍会执行,会触发空引用异常;另外Encoding.UTF8.GetString(Encoding.ASCII.GetBytes(inputLine))是冗余转换,结果与原字符串完全一致。
  3. 代码中创建了StreamWriter但未使用,属于无效资源占用。
解决方案

方案1:修改JS客户端,发送标准换行符

将JS中的发送内容改为带标准换行符的格式(\r\n或\n),触发ReadLine的返回逻辑:

const net = require('net');

const client = new net.Socket();

client.connect(1234, '192.168.2.13', () => {
  console.log('Connected to server');
  client.write("Hello server\r\n"); // 用\r\n触发C#的ReadLine
});

方案2:修改C#代码,不依赖行读取(更灵活)

如果需要兼容任意输入格式,避免依赖换行符,可以直接读取字节流:

while (true)
{
    using TcpClient client = listener.AcceptTcpClient();
    using NetworkStream stream = client.GetStream();
    byte[] buffer = new byte[1024];
    int bytesRead;

    try
    {
        // 循环读取流数据,直到客户端断开连接
        while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
        {
            string receivedData = Encoding.ASCII.GetString(buffer, 0, bytesRead);
            Console.WriteLine($"收到数据: {receivedData}");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"错误: {ex.Message}");
    }

    Console.WriteLine("与客户端的连接已断开");
}

优化原C#代码(保留行读取逻辑)

若坚持使用ReadLine,需修正冗余逻辑并确保客户端发送正确换行符:

while (true)
{
    using TcpClient client = listener.AcceptTcpClient();
    using NetworkStream stream = client.GetStream();
    using StreamReader reader = new StreamReader(stream, Encoding.ASCII);

    try
    {
        string inputLine;
        // 读取直到流结束(客户端断开)
        while ((inputLine = reader.ReadLine()) != null)
        {
            Console.WriteLine(inputLine);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"错误: {ex.Message}");
    }

    Console.WriteLine("与客户端的连接已断开");
}

内容的提问来源于stack exchange,提问作者Indy Osinga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 22:25:30