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

将C#编写的TCP客户端代码转换为Node.js代码的实现需求

Converting C# TCP Client Code to Node.js

Let's first break down what your original C# code does, then map that logic directly to Node.js using the built-in net module:

Original C# Logic Recap

  1. Establishes a TCP connection to the target HOST and port
  2. Creates a stream writer to send a JSON-formatted message string
  3. Flushes the writer to ensure all data is sent immediately
  4. Writes a single byte with value 0 to the stream
  5. Closes the TCP connection

Complete Node.js Implementation

Here's the full code that mirrors this behavior, with comments linking each step to your C# code:

const net = require('net');

// Replace these with your actual target values
const HOST = 'your-target-host';
const port = 1234;
const message = 'your-message-content';

// Create and connect the TCP client (equivalent to new TcpClient() + Connect())
const client = net.connect(port, HOST, () => {
  console.log('Connected to TCP server');

  // Build the identical JSON string as your C# code
  const str = `{ "message" : "${message}" }`;

  // Send the JSON string (equivalent to streamWriter.Write(str))
  client.write(str, () => {
    // After the string is sent, write the 0-byte (equivalent to stream.WriteByte(0))
    client.write(Buffer.from([0]), () => {
      // Close the connection once all data is sent (equivalent to tcpClient.Close())
      client.end();
    });
  });
});

// Handle connection errors (good practice for robustness)
client.on('error', (err) => {
  console.error('TCP connection error:', err.message);
});

// Handle connection closure
client.on('close', () => {
  console.log('TCP connection closed');
});

Key Notes:

  • Node.js's net module uses asynchronous callbacks instead of C#'s synchronous methods. The net.connect callback runs only after the connection is successfully established.
  • Unlike C#'s StreamWriter.Flush(), Node.js's socket.write() automatically handles flushing data to the network. We use the write callback to ensure the JSON string is fully sent before writing the 0-byte.
  • Buffer.from([0]) creates a Node.js Buffer containing a single byte with value 0, matching your C# stream.WriteByte((byte)0) call exactly.
  • client.end() gracefully closes the connection, just like tcpClient.Close() in C#.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:15:07