net之socket的通信
Client.js:
var net = require('net');
var client = new net.Socket();
client.setEncoding('utf8');
client.connect(8431, '127.0.0.1', function () {
console.log('已连接到服务器!');
client.write('你好.');
});
client.on('data', function (data) {
console.log('已收到服务器端的数据:' + data);
});
client.on('erro', function (err) {
console.log('与服务器连接时发生了一个错误,错误编码为:' + err.code);
client.destroy();
});
Server.js:
var net = require('net');
var server = net.createServer();
server.on('connection',function (socket) {
console.log('客户端与服务器端链接已建立');
socket.setEncoding('utf8');
socket.on('data',function (data) {
console.log('已接收客户端发送的数据:'+data);
socket.write('确认数据:'+data)
});
});
server.listen(8431,'127.0.0.1');