Guilherme C. Souza
Guilherme C. Souzaā€¢3y ago

Am I closing this server wrongly? The port is not free for a new listener! (`AddrInUse`)

const server = Deno.listen({ port: 80 });

(async function(){

for await(const conn of server){

(async function(){

const httpConn = Deno.serveHttp(conn);

for await(const reqEvent of httpConn){

reqEvent.respondWith(new Response('res.stream', {
status: 200
}));

}

})();

}

})();

const res = await fetch('http://localhost');
res.body?.cancel()
server.close();

// Port 80 is still in use here??

const newServer = Deno.listen({ port: 80 });
newServer.close();
const server = Deno.listen({ port: 80 });

(async function(){

for await(const conn of server){

(async function(){

const httpConn = Deno.serveHttp(conn);

for await(const reqEvent of httpConn){

reqEvent.respondWith(new Response('res.stream', {
status: 200
}));

}

})();

}

})();

const res = await fetch('http://localhost');
res.body?.cancel()
server.close();

// Port 80 is still in use here??

const newServer = Deno.listen({ port: 80 });
newServer.close();
3 Replies
Doctor šŸ¤–
Doctor šŸ¤–ā€¢3y ago
Looking at the docs I'd guess so, but it probably needs to sleep for a second for stuff outside of javascript to release it. Try doing await new Promise(a => setTimeout(_ => a(true), 0)) just after the server.close()
Guilherme C. Souza
Guilherme C. SouzaOPā€¢3y ago
It does help. Shouldn't Deno take care of it internally? Hopefully with some Promise I can wait on to make sure the port is released? This does work as expected in Node. Meaning I can bring a new server up once the close event is fired in the old one.
Doctor šŸ¤–
Doctor šŸ¤–ā€¢3y ago
Idk. Iā€™m guessing Deno releases it on its end and the OS just needs a bit of time to validate it or whatever. If sleeping for 0ms worked then you could wrap that Deno close in a promise.
await new Promise(a => {
server.close()
setTimeout(_ => a(true), 0)
})
await new Promise(a => {
server.close()
setTimeout(_ => a(true), 0)
})