Node.js中net.createServer()返回net.Server还是net.Socket?
Clarifying
net.createServer() Return Value vs. Callback Parameter Hey there! Let's break down this confusion you're having with Node.js's net module—it's a common point of mix-up for folks new to socket programming, so you're not alone.
First, let's get the core fact straight:
net.createServer()absolutely returns a<net.Server>object—this is your server instance. You use it to start listening for incoming connections withserver.listen(), shut down the server withserver.close(), or listen for server-level events likelisteningorclose.
So why does the example look like it's working with a <net.Socket>? Because the callback function you pass to createServer receives a <net.Socket> instance as its parameter! Here's how that plays out in code:
const net = require('net'); // createServer returns the <net.Server> instance, stored in 'server' const server = net.createServer((socket) => { // 'socket' here is a <net.Socket> object representing the individual client connection // Since Socket is a duplex stream, you can use methods like pipe() to handle data flow socket.pipe(socket); // Echoes incoming data back to the client }); // We use the <net.Server> instance to start listening for connections server.listen(3000, () => { console.log('Server listening on port 3000'); });
To put it simply:
- The
<net.Server>is the "manager" that handles incoming connection requests. - Every time a client connects, the server creates a new
<net.Socket>object to represent that specific connection. This is what gets passed to your callback, and it's the object you use to send/receive data with that client (hence thepipe()method, which is a stream API method).
The example focuses on handling the client connection, so it's using the Socket instance heavily—but the return value of createServer is definitely the Server object that lets you control the overall service.
内容的提问来源于stack exchange,提问作者Prem
相关产品推荐
相关产品推荐

