Skip to content

Instantly share code, notes, and snippets.

@leomao
Created March 7, 2017 03:23
Show Gist options
  • Save leomao/cdbbd1b4beb62d00c7752cdbb83dded5 to your computer and use it in GitHub Desktop.
Save leomao/cdbbd1b4beb62d00c7752cdbb83dded5 to your computer and use it in GitHub Desktop.
socket in node
const net = require('net');
socket = net.createConnection(54321);
socket.on('data', (data) => {
console.log(data.toString().trim());
});
socket.on('end', () => {
console.log('socket end');
socket.end();
});
//socket.setKeepAlive(true);
socket.write('hello~');
setTimeout(() => {
if (!socket.destroyed)
socket.write('hello again XD\n');
else
console.log('qq');
}, 3000);
const net = require('net');
server = net.createServer((socket) => {
socket.setTimeout(2000, () => {
socket.end();
});
socket.on('data', (data) => {
console.log(data.toString().trim());
socket.write('hi client');
});
socket.on('end', () => {
console.log('client bye');
});
});
server.listen(54321, () => {
console.log(`listening at localhost:54321`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment