net模块的组成部分
下面整理出了整个net模块的知识结构,和各个事件、方法、属性的用法
net.Server类
net.Socket类
事件
方法
属性
工厂方法
练习代码
netServer
var net=require("net"); /**
* 创建server
*/
function t1(){
var server=net.createServer(function(socket){
//socket.end("good bye!");
socket.write("hello,i'm server!");
console.log("client connected! %j:%j",socket.remoteAddress,socket.remotePort);
socket.on("data",function(data){
console.log("recived from client:",data.toString());
})
socket.on("close",function(had_error){
if(!had_error){
console.log("client closed success! %j:%j",socket.remoteAddress,socket.remotePort);
}
else{
console.log("client close error! %j:%j",socket.remoteAddress,socket.remotePort);
}
})
socket.on("error",function(err){
console.log("!!!err!!!",err);
});
//setTimeout(function(){
// socket.end("我结束了","utf8");
//},3000);
});
server.listen({
port:8889
},function(){
var address=server.address();
console.log(" opened server on address %j ",address);
}); var a=1;
}
t1();
netSocket
var net = require("net"); /**
* 初始化net clientSocket对象,测试发送数据,关闭连接
*/
function t1(autoclose){
var inteval;
var socket1=new net.Socket({
readable:true,
writable:true,
allowHalfOpen:true
});
socket1.on("data",function(data){
console.log("recived from server:"+data.toString());
});
socket1.on("close",function(){
console.log(" client closed success ");
});
socket1.on("error",function(err){
console.log(" client error: ",err);
});
socket1.connect({
host:"localhost",
port:8889
},function(){
console.log(" server connected");
inteval=setInterval(function(){
socket1.write("hello,i'm client!"+Math.random())
},3000)
});
if(autoclose){
setTimeout(function(){
socket1.destroy();
clearInterval(inteval)
//socket1.end("我结束了","utf8");
},3000);
}
} /**
* 通过net.connect创建clientSocket对象
*/
function t2(){
var client = net.connect({port: 8889},
function() { //'connect' listener
console.log('connected to server!!!');
client.write('world!\r\n');
});
client.on('data', function(data) {
console.log(data.toString());
//client.end();
});
client.on('end', function() {
console.log('disconnected from server');
}); } t1(false);
t1(true);
//t2();
//for(var i=0;i<1000;i++){
// console.log("连接个数:",i+1);
// t1(false);
//}
下图为server控制台的截图
使用Ctrl+C关闭client,clientsocket意外结束时,会触发error事件,随后触发close事件