nodejs複習04

TCP/UDP網絡應用

建立TCP服務器客戶端

  • socket套接字對象實例,是對TCP協議的一個基本封裝接口
  • clientt套接字對象實例
//server.js
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 9694;

var server = net.createServer(function (socket) { 

    console.log('Server listening on ' + HOST + ':' + PORT);
    console.log('CONNECTED: ' + socket.remoteAddress + ':' + socket.remotePort);

    socket.on('data', function (data) {
      console.log('DATA ' + socket.remoteAddress + ':"' + data + '"');
      socket.write('Server write: this is server')
    })

    socket.on('close', function (data) {
      console.log('CLOSED: ' + socket.remoteAddress + ' ' + socket.remotePort);
    })
})

server.listen(PORT, HOST)


//client.js
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 9694;

var client = net.connect(PORT, HOST, function () {
    console.log('client connected');
    client.write('client write: this is client');
})

client.on('data', function (data) {
    console.log(data.toString());
    client.end();
})

client.on('end', function () {
    console.log('client disconnected');
})
  • 關閉端口的方法
List open files on a port and copy PID

lsof -i :<port>
Kill it with fire :)

kill -9 <PID>

另外一種方法建立服務器

var net = require('net');
var HOST = '127.0.0.1';
var PORT = 9694;

var server = net.createServer()

server.listen(PORT, HOST)

server.on('listening', function () {
        var addr = server.address()   //獲取服務器地址,必須在listening事件以後
    console.log('Server listening on ' + addr.address + ':' + addr.port);
})

server.on('connection', function (socket) {
    console.log('CONNECTED: ' + socket.remoteAddress + ':' + socket.remotePort);

    socket.on('data', function (data) {
        console.log(data.toString());
        socket.write('server write: this is server')
    })

    socket.on('close', function () {
        console.log('CLOSED: ' + socket.remoteAddress + ' ' + socket.remotePort);
        server.close();
    })
})

server.on('error', function (err) {
    console.log('Error occurred: ' + err.message);
})

server.on('close', function () {
    console.log('server is closed');
})

得到當前服務器鏈接數

server.getConnections(function (err, count) {
        console.log(count);
})

套接字地址

//套接字綁定的IP地址,端口
socket.localAddress
socket.localPort
socket.address() //與server.address()相同

//遠程地址
socket.remoteAddress
socket.remotePort

//套接字接受和發送數據的字節長度
socket.on('data', function (data) {
    console.log(socket.bytesRead);  //
    console.log(data.toString());
    socket.write('server write: this is server')
    console.log(socket.bytesWritten);  //
})

控制套接字數據流

var bSockData = true

server.on('connection', function (socket) {

    if(bSockData) {
        sock.resume();  //暫停data事件
        bSockData = false
    } else {
        socket.pause();  //繼續data事件
        bSockData = true
    }

    socket.on('data', function (data) {})

    socket.on('close', function () {})
})

建立UDP服務器客戶端

  • 建立socket使用參數udp4/udp6,分別對應Ipv4/Ipv6,前者使用更多
  • UDP數據報發送給服務器後,服務器通常不能回寫,由於該協議就是爲例快速發送數據包
//server.js
var dgram = require('dgram')
var HOST = '127.0.0.1'
var PORT = 12345;

//建立一個udp4類型的數據報套接字

var server = dgram.createSocket('udp4')

server.on('listening', function () {
    var address = server.address();
    console.log('UDP Server listening on ' + address.address + ":" + address.port);
})

server.on('message', function (message, remote) {
    console.log('UDP Server received from ' + remote.address + ':' + remote.port);
    console.log('-' + message);
    server.close()
})

server.on('error', function (err) {
    console.log('server error: ' + err.stack);
    server.close()
})

    server.on('close', function () {
    console.log('server closed');
})

//綁定主機和端口
server.bind(PORT, HOST)


//client.js
var dgram = require('dgram')
var HOST = '127.0.0.1'
var PORT = 12345;

var message = new Buffer('UDO Client to server');

var client = dgram.createSocket('udp4')

client.send(message, 0, message.length, PORT, HOST, 
    function (err, bytes) {
        if(err) throw err;
        console.log('client send to: ' + HOST + ":" + PORT);
        console.log('-' + bytes);
        client.close();
})


client.on('close', function () {
    console.log('client closed');
})

UDP廣播服務

  • UDP廣播和單播的不一樣就是通訊IP地址不一樣,廣播使用255.255.255.255發送到同一廣播上的每一個主機
  • 廣播不會被路由器轉發
//server.js
.....
//因爲接受客戶端廣播數據報,僅僅綁定端口號
server.bind(PORT)


//client.js
var HOST = '255.255.255.255'
.....
client.bind(function () {
    client.setBroadcast(true)   //廣播
})

簡單的聊天應用

var net = require('net')
var HOST = '127.0.0.1'
var PORT = 6688

var clientList = []

var server = net.createServer();

server.on('connection', function(client) {
    clientList.push(client);
    client.name = client.remoteAddress + ":" + client.remotePort
    broadcast('him ' + client.name + ' join in!\r\n', client)
    client.write('hi, ' + client.name + '!\r\n')

    client.on('data', function (data) {
        broadcast(client.name + ' say:' + data + '\r\n', client)
    })

    client.on('end', function () {
        broadcast('hi,' + client.name + ' quit!\r\n', client)
        clientList.splice(clientList.indexOf(client), 1)
    })
})

function broadcast(message, client) {
    var cleanup = [];
    for (var i = 0, len = clientList.length; i < len; i++) {
        var o_client = clientList[i]
        if(client !== o_client) {
            if(o_client.writable) {
                o_client.write(message)
            } else {
                cleanup.push(o_client)
                o_client.destroy()
            }
        }
    }
    for (var i = 0; i < cleanup.length; i++) {
        clientList.splice(clientList.indexOf(cleanup[i]), 1)
    }
}

server.listen(PORT, HOST)
  • 測試telnet 127.0.0.1 6688
相關文章
相關標籤/搜索