W3Cschool
恭喜您成為首批注冊(cè)用戶(hù)
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
net模塊用于底層的網(wǎng)絡(luò)通信。
下面代碼打開(kāi)一個(gè)服務(wù)器端Socket接口,用來(lái)接受客戶(hù)端的數(shù)據(jù)。
var serverPort = 9099;
var net = require('net');
var server = net.createServer(function(client) {
console.log('client connected');
console.log('client IP Address: ' + client.remoteAddress);
console.log('is IPv6: ' + net.isIPv6(client.remoteAddress));
console.log('total server connections: ' + server.connections);
// Waiting for data from the client.
client.on('data', function(data) {
console.log('received data: ' + data.toString());
// Write data to the client socket.
client.write('hello from server');
});
// Closed socket event from the client.
client.on('end', function() {
console.log('client disconnected');
});
});
server.on('error',function(err){
console.log(err);
server.close();
});
server.listen(serverPort, function() {
console.log('server started on port ' + serverPort);
});
上面代碼中,createServer方法建立了一個(gè)服務(wù)端,一旦收到客戶(hù)端發(fā)送的數(shù)據(jù),就發(fā)出回應(yīng),同時(shí)還監(jiān)聽(tīng)客戶(hù)端是否中斷通信。最后,listen方法打開(kāi)服務(wù)端。
客戶(hù)端Socket接口用來(lái)向服務(wù)器發(fā)送數(shù)據(jù)。
var serverPort = 9099;
var server = 'localhost';
var net = require('net');
console.log('connecting to server...');
var client = net.connect({server:server,port:serverPort},function(){
console.log('client connected');
// send data
console.log('send data to server');
client.write('greeting from client socket');
});
client.on('data', function(data) {
console.log('received data: ' + data.toString());
client.end();
});
client.on('error',function(err){
console.log(err);
});
client.on('end', function() {
console.log('client disconnected');
});
上面代碼連接服務(wù)器之后,就向服務(wù)器發(fā)送數(shù)據(jù),然后監(jiān)聽(tīng)服務(wù)器返回的數(shù)據(jù)。
DNS模塊用于解析域名。resolve4方法用于IPv4環(huán)境,resolve6方法用于IPv6環(huán)境,lookup方法在以上兩種環(huán)境都可以使用,返回IP地址(address)和當(dāng)前環(huán)境(IPv4或IPv6)。
var dns = require('dns');
dns.resolve4('www.pecollege.net', function (err, addresses) {
if (err)
console.log(err);
console.log('addresses: ' + JSON.stringify(addresses));
});
dns.lookup('www.pecollege.net', function (err, address, family) {
if (err)
console.log(err);
console.log('addresses: ' + JSON.stringify(address));
console.log('family: ' + JSON.stringify(family));
});
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話(huà):173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: