Last active
February 4, 2025 15:14
-
-
Save mattfysh/d5e82f79b976180f4765fb6dd0d77c34 to your computer and use it in GitHub Desktop.
Bun socket listener invoked twice [intermittent]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import net from 'node:net' | |
import { spawn } from 'bun' | |
const ready = Promise.withResolvers<number>() | |
const server = spawn({ | |
cmd: ['bun', 'server.ts'], | |
stdio: ['inherit', 'inherit', 'inherit'], | |
serialization: 'json', | |
ipc: port => ready.resolve(port), | |
onExit: (_, exitCode) => { | |
if (exitCode) { | |
console.error(`Runtime exited with code: ${exitCode}`) | |
process.exit(exitCode) | |
} | |
}, | |
}) | |
const socket = net.createConnection({ port: await ready.promise }) | |
const req = JSON.stringify({ test: true }) | |
const result = await new Promise((resolve, reject) => { | |
socket.on('connect', () => { | |
socket.write(`${req}\n`) | |
socket.on('data', (data: Buffer) => { | |
try { | |
const msg = JSON.parse(data.toString()) | |
resolve(msg) | |
} catch(e) { | |
console.error('onData error', e) | |
reject(e) | |
} | |
}) | |
}) | |
}) | |
console.log('result', JSON.stringify(result)) | |
server.kill() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import net from 'node:net' | |
function start() { | |
const server = new net.Server(socket => { | |
console.log('socket connected', socket.localPort, socket.remotePort) | |
socket.on('data', async data => { | |
try { | |
const msg = JSON.parse(data.toString()) | |
socket.end(JSON.stringify({ ping: 'pong', msg })) | |
} catch(e) { | |
console.error('fatal error', e) | |
const msg = e instanceof Error ? e.message : String(e) | |
socket.end(JSON.stringify({ error: msg })) | |
} | |
}) | |
}) | |
server.listen(0) | |
const addr = server.address() | |
if (addr && typeof addr === 'object') { | |
return addr | |
} else { | |
throw new Error('NOADDR') | |
} | |
} | |
try { | |
if (!process.send) { | |
throw new Error('Unable to establish communication with parent') | |
} | |
const addr = start() | |
process.send(addr.port) | |
} catch (e) { | |
console.error(e) | |
process.exit(1) | |
} |
Cannot reproduce.
@guest271314 i've updated the gist, can you try to reproduce now?
I did. Nothing changed. Except the OS froze the last time I rand the code. What is the purpose of starting and stopping 100 times?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
run this in the terminal, you should see the socket connection listener sometimes fired twice: