Created
February 26, 2019 06:29
-
-
Save lqqyt2423/17dc6ba688bcc1d61413e66f3ffddb1b to your computer and use it in GitHub Desktop.
node tcp 示例
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
// server.js | |
'use strict'; | |
const net = require('net'); | |
const server = net.createServer(function (socket) { | |
socket.setEncoding('utf-8'); | |
// 新的连接 | |
socket.on('data', function (data) { | |
console.log(data); | |
// console.log(data.toString()); | |
socket.write('你好'); | |
}); | |
socket.on('end', function () { | |
console.log('连接断开'); | |
}); | |
socket.write('示例:\n'); | |
}); | |
server.listen(8124, function () { | |
console.log('server bound'); | |
}); | |
// client.js | |
'use strict'; | |
const net = require('net'); | |
const client = net.connect({ port: 8124 }, function () { | |
console.log('client connected'); | |
client.write('hello\n'); | |
}); | |
client.setEncoding('utf-8'); | |
client.on('data', function (data) { | |
console.log(data); | |
// console.log(data.toString()); | |
client.end(); | |
}); | |
client.on('end', function () { | |
console.log('client disconnected'); | |
}); | |
// echo.js | |
'use strict'; | |
const net = require('net'); | |
const server = net.createServer(function (socket) { | |
socket.write('Echo server\n'); | |
socket.pipe(socket); | |
}); | |
server.listen(8124); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment