重拾node第一天

// const http = require('http') // 引入模块
// http.createServer(function (req,res) {
// 	// 成功或者失败两个状态
// 	res.writeHead(200,{'Content-Type':'text/plain'});
// 	res.end('123,卧槽!');
// }).listen(8100,'127.0.0.1');
// // 本地接口127.0.0.1
// console.log('Server running at http://127.0.0.1:8100/');

const net = require('net') // 引入net模块
const chatServer = net.createServer() // 创建一个聊天服务器
clientList = [] // 定义一个空数组保存客户状态
chatServer.on('connection',function (client) { // client代表相应的状态 监听链接状态connection
	// client.write('nihao,123');
	// client.write('123,123');
	// 客户名称为客户地址家客户端口
	client.name = client.remoteAddress + ':' + client.remotePort
	client.write(`fuck,you,${client.name}`)
	clientList.push(client) // 监听到用户连接上这个这台服务器的时候 将这个client对象添加到clientList数组里面
	// 返回以上的内容以后执行关闭方法
	// client.end()
	client.on('data',function(data) { // 监听数据事件
		// 监听数据 data 为用户输入的数据
		// for(let i = 0;i<clientList.length;i++) {
		// 	// 多个用户同时发送数据
		// 	clientList[i].write(data)
		// }
		broadcast(data,client)
		// console.log(data)
	})
	client.on('end',function () {
		clientList.splice(clientList.indexOf(client),1)
		 //splace删除指定位置字符串 第二个表示数量,indexof返回首次出现的位置
	})
	client.on('error',function(data){
		console.log(data)
	})
	function broadcast(message,client) { // message为输入的消息 client为用户
		let cleanup = []
		for (let i = 0;i < clientList.length; i++) {
			if (client !== clientList[i]) {
				// 如果用户的端口号与地址不匹配
				if (clientList[i].writable) { // writable可以检测读写状态
					clientList[i].write(client.name + 'say' + message)
				} else {
					cleanup.push(clientList[i]) //如果不可写入
					clientList[i].destroy() // 调用destroy方法节点死亡
				}
			}
		}

		for (i = 0 ;i<cleanup.length;i++) { // 此处的i只作用于当前for循环
			clientList.splice(clientList.indexOf(cleanup[i]),1)
		}
	}
})
chatServer.listen(9000) // 监听9000端口
原文地址:https://www.cnblogs.com/wangjiahui/p/12398028.html