Created
January 6, 2018 09:57
-
-
Save SuperHuangXu/f4272741c0d5ac5c431bb0dc9bb518fc to your computer and use it in GitHub Desktop.
nodejs中net模块(TCP)的基本使用方法
This file contains 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
const net = require('net'); | |
// 客户端 | |
const client = net.connect({port: 8124}, () => { | |
//'connect' listener | |
console.log('connected to server!'); | |
client.write('client send...\n'); | |
}); | |
client.write('world!\r\n'); | |
client.on('data', (data) => { | |
console.log(data.toString()); | |
client.end(); | |
}); | |
client.on('end', () => { | |
console.log('disconnected from server'); | |
}); |
This file contains 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
'use strict'; | |
const net = require('net'); | |
// 服务端 | |
const server = net.createServer((socket) => { | |
console.log('client connected'); | |
// socket是一个可读可写流。 | |
socket.on('end', () => { | |
console.log('client disconnected'); | |
}); | |
socket.write('hello\r\n'); | |
socket.pipe(socket); | |
}); | |
server.on('error', (err) => { | |
throw err; | |
}); | |
server.listen(8124, () => { | |
console.log('server bound'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment