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...