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

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 with server.listen(), shut down the server with server.close(), or listen for server-level events like listening or close.

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 the pipe() 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:33:42