将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
- Establishes a TCP connection to the target
HOSTandport - Creates a stream writer to send a JSON-formatted message string
- Flushes the writer to ensure all data is sent immediately
- Writes a single byte with value
0to the stream - 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
netmodule uses asynchronous callbacks instead of C#'s synchronous methods. Thenet.connectcallback runs only after the connection is successfully established. - Unlike C#'s
StreamWriter.Flush(), Node.js'ssocket.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 value0, matching your C#stream.WriteByte((byte)0)call exactly.client.end()gracefully closes the connection, just liketcpClient.Close()in C#.
内容的提问来源于stack exchange,提问作者Maverick
相关产品推荐
相关产品推荐

