server.listen()
啟動服務器偵聽連接。 net.Server 可以是 TCP 或 IPC 服務器,具體取決於它所聽的內容。
可能的簽名:
server.listen(handle[, backlog][, callback])- server.listen(options[, callback])
用於 IPC 服務器server.listen(path[, backlog][, callback])server.listen([port[, host[, backlog]]][, callback])用於 TCP 服務器
這個函數是異步的。當服務器開始偵聽時,將發出 事件。最後一個參數'listening' callback 將被添加為 事件的偵聽器。'listening'
所有listen() 方法都可以采用backlog 參數來指定待處理連接隊列的最大長度。實際長度將由操作係統通過 sysctl 設置確定,例如 Linux 上的 tcp_max_syn_backlog 和 somaxconn。此參數的默認值為 511(不是 512)。
所有 都設置為net.Socket SO_REUSEADDR(有關詳細信息,請參見 )。socket(7)
當且僅當在第一次 server.listen() 調用期間出現錯誤或已調用 server.close() 時,才能再次調用 server.listen() 方法。否則,將引發 ERR_SERVER_ALREADY_LISTEN 錯誤。
收聽時最常見的錯誤之一是 EADDRINUSE 。當另一台服務器已經在偵聽請求的 port /path /handle 時,就會發生這種情況。處理此問題的一種方法是在一定時間後重試:
server.on('error', (e) => {
if (e.code === 'EADDRINUSE') {
console.log('Address in use, retrying...');
setTimeout(() => {
server.close();
server.listen(PORT, HOST);
}, 1000);
}
});
相關用法
- Node.js net.Server.address()用法及代碼示例
- Node.js net.Socket.setTimeout(timeout[, callback])用法及代碼示例
- Node.js net.isIP(input)用法及代碼示例
- Node.js net.createConnection(options[, connectListener])用法及代碼示例
- Node.js net.isIPv6(input)用法及代碼示例
- Node.js net.createServer([options][, connectionListener])用法及代碼示例
- Node.js net.BlockList.check(address[, type])用法及代碼示例
- Node.js net.isIPv4(input)用法及代碼示例
- Node.js new assert.AssertionError(options)用法及代碼示例
- Node.js new AsyncResource(type[, options])用法及代碼示例
- Node.js new stream.Duplex(options)用法及代碼示例
- Node.js new stream.Readable([options])用法及代碼示例
- Node.js new Console(options)用法及代碼示例
- Node.js new URLSearchParams(obj)用法及代碼示例
- Node.js new crypto.Certificate()用法及代碼示例
- Node.js new stream.Writable([options])用法及代碼示例
- Node.js new URLSearchParams(iterable)用法及代碼示例
- Node.js new Agent([options])用法及代碼示例
- Node.js new vm.SourceTextModule(code[, options])用法及代碼示例
- Node.js new stream.Transform([options])用法及代碼示例
- Node.js new PerformanceObserver(callback)用法及代碼示例
- Node.js new URL(input[, base])用法及代碼示例
- Node.js new URLSearchParams(string)用法及代碼示例
- Node.js new assert.CallTracker()用法及代碼示例
- Node.js ServerHttp2Stream http2stream.pushStream(headers[, options], callback)用法及代碼示例
注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 net.Server.listen()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
