joyent/node — Issue #2867: Cannot close dgram socket from listening event
Author: tjfontaine
Created: 2012-03-04 20:00:01+00:00
State: open

```javascript
var dgram = require('dgram');

var socket = dgram.createSocket('udp4');

socket.on('listening', function () {
socket.close();
});

socket.bind();
```

fails with

```
node udp.js

node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Cannot set property 'onmessage' of null
at Socket._startReceiving (dgram.js:315:26)
at dgram.js:128:14
at lookup (dgram.js:49:12)
at UDP.lookup4 [as lookup] (dgram.js:59:10)
at Socket.bind (dgram.js:120:16)
```

It seems like a sane solution would be to swap https://github.com/joyent/node/blob/master/lib/dgram.js#L127..L128 such the handlers are set before `.close` sets `_handle = null`

This pattern succeeds with tcp sockets.