1.NET学习

1.Server.js

//ServerTCP.js
//REF https://nodejs.org/dist/latest-v6.x/docs/api/net.html
//REF http://www.hacksparrow.com/tcp-socket-programming-in-node-js.html
/*
[A] NET module function[.isIP() | .isIPv4()  | .isIPv6() | .createServer()  | .connect()  | .createConnection()]
①net.createServer([options][,connectionListener]),automatically set as listener for the "connection" event
    -return net.Server
    -callback(net.Socket)
②net.connect(port[,host][,connectListener]) //The connectListener parameter will be added as a listener for the 'connect' event once.
③net.createConnection(options[,connectListener]) //Passing timeout as an option will call socket.setTimeout() after the socket is created, but before it is connecting.

[B] NET module class[net.Server | net.Socket]
①net.Server[is an EventEmitter]
 -"close"-Emitted when the server closes. Note that if connections exist, this event is not emitted until all connections are ended.
 -"connection"[net.Socket]-Emitted when a new connection is made. socket is an instance of net.Socket.
 -"error"[Error]-Emitted when an error occurs. The 'close' event will be called directly following this event.
 -"listening"-Emitted when the server has been bound after calling server.listen().
 -server.address() //返回一个port,host信息的对象[Don't call server.address() until the 'listening' event has been emitted.]
 -server.close([callback]) //emits a 'close' event. The optional callback will be called once the 'close' event occurs.
 -server.getConnections(callback) //获取连接个数,Callback should take two arguments err and count.
 -server.listen([port][,hostname][,backlog][,callback]) //When the server has been bound, 'listening' event will be emitted. //The last parameter callback will be added as a listener for the 'listening' event.
 -server.listening //A Boolean indicating whether or not the server is listening for connections.
 -server.maxConnections //Set this property to reject connections when the server's connection count gets high.

②net.Socket[is an EventEmitter]
    //created by the user and used as a client (with connect())
    //created by Node.js and passed to the user through the 'connection' event of a server.
 -"close"[Boolean]-Emitted once the socket is fully closed
 -"connect"-Emitted when a socket connection is successfully established. See connect().
 -"data"[Buffer]-Emitted when data is received.  Encoding of data is set by socket.setEncoding().
        Note that the data will be lost if there is no listener when a Socket emits a 'data' event.
 -"drain"-Emitted when the write buffer becomes empty. Can be used to throttle uploads.
 -"end"-Emitted when the other end of the socket sends a FIN packet.
 -"lookup"-Emitted after resolving the hostname but before connecting.
 -"timeout"-Emitted if the socket times out from inactivity. This is only to notify that the socket has been idle. The user must manually close the connection.

 -socket.address()  //返回内容同server.address()
 -socket.bufferSize //
 -socket.bytesRead  //The amount of received bytes
 -socket.bytesWritten//The amount of bytes sent
 -socket.connect([port[,host][,connectionListener]) //Opens the conenction for a givern socket
     The connectListener parameter will be added as a listener for the 'connect' event.
     If there is a problem connecting, the 'connect' event will not be emitted, the 'error' event will be emitted with the exception.
 -socket.connecting //If true - socket.connect(options[, connectListener]) was called and haven't yet finished. Will be set to false before emitting connect event and/or calling socket.connect(options[, connectListener])'s callback.
 -socket.destroy([exception]) //Ensures that no more I/O activity happens on this socket. Only necessary in case of errors (parse error or so).
     If exception is specified, an 'error' event will be emitted and any listeners for that event will receive exception as an argument.
 -socket.destroyed //A Boolean value that indicates if the connection is destroyed or not

 -socket.localAddress //The string representation of the local IP address the remote client is connecting on
 -socket.localPort  //The numeric representation of the local port
 -socket.remoteAddress //
 -socket.remoteFamily //
 -socket.remotePort //
 -socket.pause() //Pauses the reading of data. That is, 'data' events will not be emitted
 -socket.resume() //Resumes reading after call to pause()

 -socket.setEncoding([encoding]) //Set the encoding for the socket as a Readable Stream
 -socket.write(data[,encoding][,callback]) //Sends data on socket.UTF8,return true or false.Asyc callback
 -socket.end([data][,encoding) //Half-closes the socket. i.e., it sends a FIN packet. It is possible the server will still send some data.

 -socket.setTimeout(timeout[,callback]) //设置超时时间,timeout内没有新的数据就关闭socket
 -socket.setDelay([noDelay]) //Disables the Nagle algorithm immediately fire off data
 -socket.setKeepAlive([enable][,initialDelay]) //Enable/disable keep-alive functionality

*/

const net = require("net");

const HOST = "127.0.0.1";
const PORT = 8080;
console.log(`net.isIP(HOST):${net.isIP(HOST)}`);
console.log(`net.isIPv4(HOST):${net.isIPv4(HOST)}`);
console.log(`net.isIPv6(HOST):${net.isIPv6(HOST)}`)

//listener for "connection"
const server = net.createServer((socket)=>{
    var waitTime = 15;

    //console.log 一些基础信息
    console.log("localAddress:",socket.localAddress);
    console.log("localPort:",socket.localPort);
    console.log("remoteAddress:",socket.remoteAddress);
    console.log("remotePort:",socket.remotePort);
    console.log("remoteFamily:",socket.remoteFamily);
    console.log("client connected");
    //var socketData = "";

    //console.log 连接数量
    server.getConnections((err,count)=>{
        if(err){
            console.log("getConnections error:",err.message);
        }else{
            console.log("getConnections:",count);
        }
    });

    //console.log 查看最大连接数量
    console.log(`server.maxConnections:${server.maxConnections}`);

    // listen for "end" event on socket[Emitted when the other end of the socket sends a FIN packet.]
    socket.on("end",()=>{
        console.log(`${new Date().getTime()} Disconnected from client`);
    });

    // listen for "timeout" event on socket
    socket.setTimeout(1000*waitTime,()=>{
        console.log(`No data from client in ${waitTime}s,disconnect...`);
       socket.end();//将会触发end和close事件,end后不能发数据,但是可以收数据
    })

    //listen for "error" event on socket[Emitted when an error occurs. follow by "close"event]
    socket.on("error",(err)=>{
        console.log("Error occurs:",err.message);
    })

    //listen for "close" event on socket[Emitted once the socket is fully closed]
    socket.on("close",()=>{
        console.log(`${new Date().getTime()} Socket on remotePort ${socket.remotePort} closed...`);
    });

    //listen for "data" event on socket
    socket.on("data",(data)=>{
        //socketData +=data;
        console.log("Received data from client:",data.toString());
        socket.write("Hello from TCP server Echo:"+data.toString());
        //直接把数据给pipe回去
        //socket.pipe(socket)
    });
})

//listener for "error"
server.on("error",(err)=>{
    if(err.code =="EADDRINUSE"){
        console.log(`Errors:${err.message}`);
        setTimeout(()=>{
            //触发server的close事件,但是直到所有连接结束,才会关闭服务。
            server.close();
            // grab a random port
            server.listen(()=>{
                console.log("opened server on ",server.address());
            });
        })
    }else{
        console.log(err.message);
    }
},10000);

//listener for "listening"
server.listen(PORT,HOST,()=>{
    //查看服务器是否在监听
    console.log(`Server.listening:${server.listening}`);
    //查看服务器的监听port,host,family
    console.log("Opened server on ",server.address());
    //设置服务器的最大连接数
    server.maxConnections = 4;
});

//listener for "close"
server.on("close",()=>{
    console.log("Server has closed.");
})

2.Client.js程序代码

//ClientTCP.js
const net = require("net");

const HOST = "127.0.0.1";
const PORT = 8080;

const client = net.connect({port:PORT,host:HOST},()=>{
    console.log("Connected to server");
    client.write("Hello from TCP client");
});

client.on("error",(err)=> {
    console.log("Errors occurs:",err.message);
})

client.on("data",(data)=>{

    //console.log 一些基础信息
    console.log("localAddress:",client.localAddress);
    console.log("localPort:",client.localPort);
    console.log("remoteAddress:",client.remoteAddress);
    console.log("remotePort:",client.remotePort);
    console.log("remoteFamily:",client.remoteFamily);

    console.log("received data from server:",data.toString());

    client.write("Hello again from TCP client");
    client.end();
});

// listen for "end" event on socket[Emitted when the other end of the socket sends a FIN packet.]
client.on("end",()=>{
    console.log(`${new Date().getTime()} Disconnected from server`);
});

//listen for "close" event on socket[Emitted once the socket is fully closed]
client.on("close",()=>{
    console.log(`${new Date().getTime()} Socket on remotePort ${client.remotePort} closed...`);
});

3.正常的运行结果

A. Server.js运行结果
net.isIP(HOST):4
net.isIPv4(HOST):true
net.isIPv6(HOST):false
Server.listening:true
Opened server on  { address: '127.0.0.1', family: 'IPv4', port: 8080 }
localAddress: 127.0.0.1
localPort: 8080
remoteAddress: 127.0.0.1
remotePort: 32911
remoteFamily: IPv4
client connected
server.maxConnections:4
getConnections: 1
Received data from client: Hello from TCP client
Received data from client: Hello again from TCP client
1489902564656 Disconnected from client
1489902564657 Socket on remotePort 32911 closed...

B. Client.js执行结果
Connected to server
localAddress: 127.0.0.1
localPort: 32911
remoteAddress: 127.0.0.1
remotePort: 8080
remoteFamily: IPv4
received data from server: Hello from TCP server Echo:Hello from TCP client
localAddress: 127.0.0.1
localPort: 32911
remoteAddress: 127.0.0.1
remotePort: 8080
remoteFamily: IPv4
received data from server: Hello from TCP server Echo:Hello again from TCP client
Errors occurs: write after end
1489902564657 Disconnected from server
1489902564657 Socket on remotePort 8080 closed...

4.注释Client.js中27/28行代码,观察socket.end()事件做什么事情

// client.write("Hello again from TCP client");
// client.end();

A. Server.js运行结果
net.isIP(HOST):4
net.isIPv4(HOST):true
net.isIPv6(HOST):false
Server.listening:true
Opened server on  { address: '127.0.0.1', family: 'IPv4', port: 8080 }
localAddress: 127.0.0.1
localPort: 8080
remoteAddress: 127.0.0.1
remotePort: 32946
remoteFamily: IPv4
client connected
server.maxConnections:4
getConnections: 1
Received data from client: Hello from TCP client
No data from client in 15s,disconnect...
1489902721937 Disconnected from client
1489902721938 Socket on remotePort 32946 closed...

B. Client.js执行结果
Connected to server
localAddress: 127.0.0.1
localPort: 32946
remoteAddress: 127.0.0.1
remotePort: 8080
remoteFamily: IPv4
received data from server: Hello from TCP server Echo:Hello from TCP client
1489902721933 Disconnected from server
1489902721933 Socket on remotePort 8080 closed...
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,039评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,223评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,916评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,009评论 1 291
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,030评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,011评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,934评论 3 416
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,754评论 0 271
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,202评论 1 309
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,433评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,590评论 1 346
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,321评论 5 342
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,917评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,568评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,738评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,583评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,482评论 2 352

推荐阅读更多精彩内容