用于创建 TCP 或 IPC server
server 实例属性和方法
const net = require('net'); const PORT = 8867; const HOST = '127.0.0.1'; const clientHandle = function (socket) { const {port, address} = socket.address(); socket.on('data', function (data) { console.log(address, port, 'on data'); socket.write('server is inline'); app.getConnections(function (error, connections) { console.log(connections); socket.destroy(); app.close(); }) }) } const app = net.createServer(clientHandle); app.listen(PORT, HOST, function () { console.log('tcp server running', app.address()); console.log(app.listening); }); app.on('listening', function () { console.log('app is listening at ', app.address()); }) app.on('connection', function (socket) { console.log('app is connection ', socket); }) app.on('error', function (err) { console.log('error', err); }) app.on('close', function () { console.log('app is close'); })
net.Socket 可以被用户创建并直接与 server 通信,在 server 中,当一个链接被接受时,可以通过监听 connection 事件触发而获得,可以使用它来与客户端通信
const net = require('net');; const PORT = 8867; const HOST = '127.0.0.1'; const client = net.Socket(); client.setEncoding('utf-8'); client.connect(PORT, HOST, function () { console.log('connect success.'); client.write('tcp client by node'); client.pause(); setTimeout(function () { client.resume(); }, 1000) }) console.log('connecting ', client.connecting); //true client.on('data', function (data) { console.log('received: ', data.toString()); }) client.on('connect', function () { console.log('address', client.address()); console.log('connecting ', client.connecting); // false console.log('localAddress', client.localAddress); console.log('localPort', client.localPort); console.log('remoteAddress', client.remoteAddress); console.log('remoteFamily', client.remoteFamily); console.log('remotePort', client.remotePort); }) client.on('error', function (err) { console.log('error', err); client.end('ssssss'); client.destroy(); console.log('destroyed', client.destroyed); })
一个工程函数,用来创建 net.Socket ,然后立即启动 connect() 方法,最终返回 socket 对象,有三种参数传入方式
net.createConnection(options[, connectListener] options 与 socket 实例的 connect 方法一致 net.createConnection(path[, connectListener] 用来连接路径 net.createConnection(port[, host][, connectListener] 连接 TCP const client = net.createConnection(PORT, HOST, function () { console.log('connect success.'); }) const client = net.createConnection({port: PORT, host: HOST}, function () { console.log('connect success.'); })
创建一个 TCP 或者 IPC 服务器,接受两个参数,第一个参数 options 可选, 第二个参数 connectionListener 监听函数,监听 connection
const app = net.createServer(function (socket) { console.log(socket); });
判断某个字符串是不是ip 地址
net.isIP('10.0.0.1') // 4 net.isIP('cats') // 0
作者:信息录入:文案编辑:视频录制:视频编辑:图片编辑:关键字修改: