博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
nodejs简易聊天室
阅读量:6875 次
发布时间:2019-06-26

本文共 2029 字,大约阅读时间需要 6 分钟。

  hot3.png

第一个nodejs简易聊天室

var net = require('net');var clients = [];function Client(stream) {  this.name = null;  this.stream = stream;}var server = net.createServer(function (stream) {  stream.setEncoding('utf-8');  var address = stream.remoteAddress;  var client = new Client(stream);  if (address === '127.0.0.1') {    client.name = 'system';    clients.push(client);  } else {    stream.write('请在10s内输入您的昵称!\n');  }  var timeout = setTimeout(function () {    if (client.name === null) {      stream.write('对不起,您已经超时!\n');      stream.end();    }  }, 10000);  stream.on('data', function(data) {    if (client.name === null) {      var name = data.match(/\S+/);      name = name[0];      var flag = false;      for (var key in clients) {        if (clients[key].name === name) {          flag = true;          stream.write('对不起,该昵称已被使用,请换个试试!\n');          break;        }      }      if (flag) {        return;      }      client.name = name;      console.log(client.name, '进入聊天室');      stream.write('欢迎您进入聊天室!\n');      clients.forEach(function(c) {        c.stream.write(client.name+' 进入聊天室!\n');      });      clients.push(client);      return;    }    clients.forEach(function(c) {      if (c !== client) {        c.stream.write(client.name+" : "+data);      }    });  });  stream.on('end', function() {    var position = -1;    clients.forEach(function(c, index) {      if (c === client) {        position = index;      }      if (c !== client && client.name !== null) {        c.stream.write(client.name+' 离开了!\n');      }    });    stream.end();    if (position >= 0) {      clients.splice(position, 1);    }  });  stream.on('error', function(err) {    var position = -1;    clients.forEach(function(c, index) {      if (c === client) {        position = index;      }      if (c !== client && client.name !== null) {        c.stream.write(client.name+' 异常退出!\n');      }    });    stream.end();    if (position >= 0) {      clients.splice(position, 1);    }  });});server.listen(8000);

转载于:https://my.oschina.net/thmz/blog/57087

你可能感兴趣的文章
中国公布北京2022年冬奥会企业赞助有关增值税政策
查看>>
四川公安严厉打击盗油犯罪:2018年缴获被盗柴油逾27吨
查看>>
创新智慧矿山解决方案 广纳集团走绿色可持续发展之路
查看>>
中消协警示:有人打“保健品岁末答谢”等幌子行骗
查看>>
品牌不能忽视的数字资产——域名为何在今天依然重要?
查看>>
贴福字、集五福、沾福气!这才是“中国福“的最优雅打开姿势
查看>>
DT时代,大数据常用的软件工具有哪些?
查看>>
十一个关于Netty的经典问答:为何选择Netty?
查看>>
深入浅出 FlatBuffers 之 Schema
查看>>
JavaScript 设计模式 : 生活中的'适配器'和'装饰者'模式
查看>>
Retrofit与Rxjava封装终结者(一)基本用法
查看>>
Weex 在饿了么前端的实践
查看>>
Element源码分析系列3-Button(按钮)
查看>>
ES6零基础教学_解析彩票项目-学习笔记(三)
查看>>
Django2 web实战01-启动项目
查看>>
玩转iOS开发:4.《Core Animation》CALayer的视觉效果
查看>>
Flutter「发布预览版 2」让 iOS 应用至臻完美
查看>>
隐式动画的性能瓶颈
查看>>
30 天精通 RxJS(24): Observable operators - multicast, refCount, publish, share
查看>>
js选择排序
查看>>