nodejs网络模块中的'connect'事件何时发出?

编程入门 行业动态 更新时间:2024-10-26 14:39:43
本文介绍了nodejs网络模块中的'connect'事件何时发出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有这个简单的 TCP 服务器:

I have this simple TCP server:

var net = require('net');

var server = net.createServer(function (socket) {

    socket.on('connect', function() {
        console.log("New client!");
    });

});

server.listen(8000, function(){
    console.log("server running...")
});

然后我有另一个文件 client.js:

and then I have another file as client.js:

var net = require('net');

var client = net.connect({port: 8000},
    function() { 
    console.log('client connected');
});

client.on('error', console.error);

我在一个终端窗口中运行服务器,然后在另一个窗口中运行客户端,并希望看到服务器日志新客户端".虽然,这不会发生.那么,'connect' 事件究竟何时发出?

I run server in one terminal window and then I run client in other window and expect to see server log "New Client". Although, that doesn't happen. So, when is the 'connect' event exactly emitted?

推荐答案

net.createServer 将给定函数设置为 connection 事件.

net.createServer sets the given function as a listener to the connection event.

换句话说,在服务器端,当您收到回调时,套接字已经连接,并且您尝试侦听的事件不会在已连接的套接字上发出.

In other words, on the server side, the socket is already connected when you get the callback, and the event you're trying to listen to isn't emitted on an already connected socket.

这篇关于nodejs网络模块中的'connect'事件何时发出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-05-01 08:55:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1406734.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模块   事件   网络   nodejs   connect

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!