1.NET學(xué)習(xí)

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() //返回一個(gè)port昭抒,host信息的對(duì)象[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) //獲取連接個(gè)數(shù),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()  //返回內(nèi)容同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]) //設(shè)置超時(shí)時(shí)間,timeout內(nèi)沒有新的數(shù)據(jù)就關(guān)閉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 一些基礎(chǔ)信息
    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 連接數(shù)量
    server.getConnections((err,count)=>{
        if(err){
            console.log("getConnections error:",err.message);
        }else{
            console.log("getConnections:",count);
        }
    });

    //console.log 查看最大連接數(shù)量
    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();//將會(huì)觸發(fā)end和close事件,end后不能發(fā)數(shù)據(jù)抱完,但是可以收數(shù)據(jù)
    })

    //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());
        //直接把數(shù)據(jù)給pipe回去
        //socket.pipe(socket)
    });
})

//listener for "error"
server.on("error",(err)=>{
    if(err.code =="EADDRINUSE"){
        console.log(`Errors:${err.message}`);
        setTimeout(()=>{
            //觸發(fā)server的close事件窥淆,但是直到所有連接結(jié)束,才會(huì)關(guān)閉服務(wù)阐滩。
            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,()=>{
    //查看服務(wù)器是否在監(jiān)聽
    console.log(`Server.listening:${server.listening}`);
    //查看服務(wù)器的監(jiān)聽port,host,family
    console.log("Opened server on ",server.address());
    //設(shè)置服務(wù)器的最大連接數(shù)
    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 一些基礎(chǔ)信息
    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.正常的運(yùn)行結(jié)果

A. Server.js運(yùn)行結(jié)果
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執(zhí)行結(jié)果
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運(yùn)行結(jié)果
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執(zhí)行結(jié)果
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...
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市症杏,隨后出現(xiàn)的幾起案子装获,更是在濱河造成了極大的恐慌,老刑警劉巖厉颤,帶你破解...
    沈念sama閱讀 219,270評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件穴豫,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡逼友,警方通過查閱死者的電腦和手機(jī)精肃,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,489評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門秤涩,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人司抱,你說我怎么就攤上這事筐眷。” “怎么了习柠?”我有些...
    開封第一講書人閱讀 165,630評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵浊竟,是天一觀的道長。 經(jīng)常有香客問我津畸,道長振定,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,906評(píng)論 1 295
  • 正文 為了忘掉前任肉拓,我火速辦了婚禮后频,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘暖途。我一直安慰自己卑惜,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,928評(píng)論 6 392
  • 文/花漫 我一把揭開白布驻售。 她就那樣靜靜地躺著露久,像睡著了一般。 火紅的嫁衣襯著肌膚如雪欺栗。 梳的紋絲不亂的頭發(fā)上毫痕,一...
    開封第一講書人閱讀 51,718評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音迟几,去河邊找鬼消请。 笑死,一個(gè)胖子當(dāng)著我的面吹牛类腮,可吹牛的內(nèi)容都是我干的臊泰。 我是一名探鬼主播,決...
    沈念sama閱讀 40,442評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼蚜枢,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼缸逃!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起厂抽,我...
    開封第一講書人閱讀 39,345評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤需频,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后修肠,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體贺辰,經(jīng)...
    沈念sama閱讀 45,802評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,984評(píng)論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了饲化。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片莽鸭。...
    茶點(diǎn)故事閱讀 40,117評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖吃靠,靈堂內(nèi)的尸體忽然破棺而出硫眨,到底是詐尸還是另有隱情,我是刑警寧澤巢块,帶...
    沈念sama閱讀 35,810評(píng)論 5 346
  • 正文 年R本政府宣布礁阁,位于F島的核電站,受9級(jí)特大地震影響族奢,放射性物質(zhì)發(fā)生泄漏姥闭。R本人自食惡果不足惜寺酪,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,462評(píng)論 3 331
  • 文/蒙蒙 一秉剑、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧杭隙,春花似錦廊敌、人聲如沸铜跑。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,011評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽锅纺。三九已至,卻和暖如春肋殴,著一層夾襖步出監(jiān)牢的瞬間囤锉,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,139評(píng)論 1 272
  • 我被黑心中介騙來泰國打工疼电, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留嚼锄,地道東北人减拭。 一個(gè)月前我還...
    沈念sama閱讀 48,377評(píng)論 3 373
  • 正文 我出身青樓蔽豺,卻偏偏與公主長得像,于是被迫代替她去往敵國和親拧粪。 傳聞我的和親對(duì)象是個(gè)殘疾皇子修陡,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,060評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容