Skip to content

Instantly share code, notes, and snippets.

@mattfysh
Last active February 4, 2025 15:14
Show Gist options
  • Save mattfysh/d5e82f79b976180f4765fb6dd0d77c34 to your computer and use it in GitHub Desktop.
Save mattfysh/d5e82f79b976180f4765fb6dd0d77c34 to your computer and use it in GitHub Desktop.
Bun socket listener invoked twice [intermittent]
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()
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)
}
@mattfysh
Copy link
Author

mattfysh commented Feb 3, 2025

run this in the terminal, you should see the socket connection listener sometimes fired twice:

for i in {1..100}; do bun index.ts; done

@guest271314
Copy link

Cannot reproduce.

@mattfysh
Copy link
Author

mattfysh commented Feb 3, 2025

@guest271314 i've updated the gist, can you try to reproduce now?

@guest271314
Copy link

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