问题描述
限时送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:关键词]
发布评论