• 重拾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端口
    
  • 相关阅读:
    mac上eclipse上运行word count
    利用hadoop自带程序运行wordcount
    mac上eclipse上配置hadoop
    在mac上安装hadoop伪分布式
    0到N数其中三个数的全排列
    【设计模式】【应用】使用模板方法设计模式、策略模式 处理DAO中的增删改查
    【设计模式】【行为型模式】策略模式
    【设计模式】【行为型模式】模板模式
    properties文件操作
    File相关操作
  • 原文地址:https://www.cnblogs.com/wangjiahui/p/12398028.html
Copyright © 2020-2023  润新知