Replies: 0 comments 1 reply
-
The behavior you're observing is due to how the In your server code, you have the following loop: for await (const chunk of socket) {
return;
} When the Here's the sequence of events in your server code:
This is why you observe the behavior where the client's socket is closed as soon as it sends the data. If you want to read one message at a time using async iterators, you can modify your code to continue the loop without the Server: const { createServer } = require('net');
async function bootstrap() {
const server = createServer(async (socket) => {
console.log('socket');
const socketIterator = socket[Symbol.asyncIterator]();
while (true) {
const { done, value } = await socketIterator.next();
if (done) break;
console.log('Received:', value.toString());
}
});
await new Promise((resolve) => {
server.listen(process.env.PORT, () => {
console.log(`listening on http://localhost:${process.env.PORT}`);
resolve();
});
});
}
bootstrap(); Client: const { connect } = require('net');
async function bootstrap() {
const socket = await new Promise((resolve) => {
const socket = connect({ host: 'localhost', port: 3003 }, () => {
resolve(socket);
});
});
socket.write('hello');
socket.end();
}
bootstrap(); In this modified code, the server keeps listening for incoming data until the socket iterator is explicitly closed, which allows you to handle each chunk of data individually. The client's socket is ended after sending the data to signal the end of communication. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hey there, I came across some behaviour with net server/client with async iterators I would like to understand and am hoping a node genius could explain to me.
If I use a socket connection in net server as an async iterator and return early it immediately causes the client to close. I was using this to read one message at a time (which I'll be switching to iterator.next() now), but am wondering if someone could explain why this behaviour happens.
happens with both node 16 and 18
Server
Client
Beta Was this translation helpful? Give feedback.
All reactions