使用nodejs的net模块创建TCP服务器
laiqun@msn.cn
|
Contents
1. 代码实现
const PORT = 18001;
const HOST = '127.0.0.1';
var net = require('net');
var clientHandler = function(socket){
console.log('someon connected');
socket.on('data',function dataHandler(data){
console.log(socket.remoteAddress,socket.remotePort,'send',data.toString());
socket.write('server received\n');
});////data 当客户端发来数据时触发
socket.on('close',function(){
console.log(socket.remoteAddress,soctet.remotePort,'disconnected');
//socket之后被销毁
});
};
var app= net.createServer(clientHandler);
app.listen(PORT,HOST);
console.log('tcp server running on tcp:://',HOST,':',PORT);
//当connect事件发生时,触发回调函数
2. 使用telnet连接服务器测试
telnet localhost 18001 会触发connect事件 输入一段字 回车,便可发送 使用netstat -antp|grep 18001
3. 创建一个TCP的client
var net = require('net');
const HOST = '127.0.0.1';
const PORT = 18001;
var tcpClient = net.SOcket();
tcpClient.connect(PORT,HOST,function(){
console.log('connect success.');
tcpClient.write('this is tcp client by nodejs');
});
tcpClient.on('data',function(data){//监听
console.log('received: ',data);
});