网站首页  汉语字词  英语词汇  考试资料  写作素材  旧版资料

请输入您要查询的考试资料:

 

标题 Node.js实现简单聊天服务器
内容
    Node.js 是一个基于Chrome JavaScript运行时建立的一个平台, 用来方便地搭建快速的,易于扩展的网络应用,今天我们来探讨下,如何使用node.js实现简单的聊天服务器
    使用Nodejs是如此简单的实现了一个简单的聊天服务器
    实现代码如下:
    var net = require('net');
    var chatServer = net.createServer(),clientList = [];
    chatServer.on("connection",function(client){
      client.name = client.remoteAddress + ":" + client.remotePort;
      client.write("Hi! "+client.name+" \n");
      clientList.push(client);
      client.on("data",function(data){
        //数据发送给客户端
        broadcast(data,client);
        // clientList[i].write(data);
      });
      client.on("end",function(){
        clientList.splice(clientList.indexOf(client),1);
      });
      client.on("error",function(e){
        console.log(e)
      });
    });
    chatServer.listen(9000)
    function broadcast(message,client){
      var cleanup = [];
      for(var i=0;i<clientList.length;i++){
        if(client != clientList[i]){
          if(clientList[i].writable){
            clientList[i].write(client.name = "says:"+message);
          }else{
            cleanup.push[clientList[i]];
            clientList[i].destory();
          }
        }
      }
    }使用过程就是:
    启动js
    node chat.js连接方式:telnet
    telnet 127.0.0.1 9000
随便看

 

在线学习网考试资料包含高考、自考、专升本考试、人事考试、公务员考试、大学生村官考试、特岗教师招聘考试、事业单位招聘考试、企业人才招聘、银行招聘、教师招聘、农村信用社招聘、各类资格证书考试等各类考试资料。

 

Copyright © 2002-2024 cuapp.net All Rights Reserved
更新时间:2025/6/8 20:41:25