日期:2014-05-16  浏览次数:20375 次

nodejs+nowjs实现聊天室
支持多房间,支持私聊,使用nowjs库,服务器端代码不到100行。需要jquery1.7.1和coffee-script.js,读者可自行下载。
重点:
1、nowjs中Group的使用,如何遍历Group内的users。
2、客户端如何异步调用服务器端函数。
3、如何与特定用户通信。
运行
引用
node app.js

在浏览器中访问http://localhost:8080

app.js
require('coffee-script');
require('./chatroomserver');


chatroomserver.coffee
coffeescript代码,重点部分已加上注释
fs = require 'fs'
url = require 'url'

html = fs.readFileSync __dirname + '/chatroom.html'
jquery = fs.readFileSync __dirname + '/../js/jquery-1.7.1.min.js'
coffeescript = fs.readFileSync __dirname + '/../js/coffee-script.js'

server = require('http').createServer((req, res)->
  pathname = url.parse(req.url).pathname
  res.end html if pathname == '/'
  res.end jquery if pathname == '/jquery.js'
  res.end coffeescript if pathname == '/coffee-script.js'
)
server.listen 8080

nowjs = require 'now'

everyone = nowjs.initialize server

rooms = {}
rooms['lobby'] = '大厅'
rooms['room1'] = '房间1'
rooms['room2'] = '房间2'
rooms['room3'] = '房间3'

onlineUsers = {} #所有在线用户

everyone.now.chckUser = (name, callback) -> #重点,使用异步方法调用
  callback onlineUsers[name] != undefined #检查是否已有同名用户

everyone.now.initlize = ->
  @now.updateRooms rooms
  @now.room = 'lobby'
  onlineUsers[@now.username] = @user.clientId
  _lobby = nowjs.getGroup @now.room
  _lobby.addUser @user.clientId
  _lobby.now.receiveMessage "[SYS]#{@now.username} 进入#{rooms[@now.room]}, 欢迎!"
  updateRoomUser @now.room

updateRoomUser = (roomid) ->#更新房间的用户
  _users = []
  _group = nowjs.getGroup roomid
  _group.getUsers (usersid) ->#用Group#getUsers(callback)方法
    _users = []
    _users.push _group['users'][userid]['now']['username'] for userid in usersid #重点:取group中的用户名,要注意group的结构
  _group.now.updateOnlineUsers _users

everyone.now.changeRoom = (newRoom) ->
  nowjs.getGroup(@now.room).removeUser(@user.clientId)
  nowjs.getGroup(@now.room).now.receiveMessage "[SYS]#{@now.username}离开#{rooms[@now.room]}进入#{rooms[newRoom]},再见!"
  updateRoomUser @now.room
  nowjs.getGroup(newRoom).addUser(@user.clientId)
  @now.room = newRoom
  nowjs.getGroup(newRoom).now.receiveMessage "[SYS]#{@now.username} 进入#{rooms[newRoom]},欢迎!"
  updateRoomUser newRoom

everyone.disconnected ->#当断开连接时,触发
  nowjs.getGroup(@now.room).now.receiveMessage "[SYS]#{@now.username}走了,再见!"
  nowjs.getGroup(@now.room).removeUser(@user.clientId)
  delete onlineUsers[@now.username]
  updateRoomUser @now.room

everyone.now.distributePersonalMessage = (to, message) -> #私聊
  self = @ #保存this
  _gruop = nowjs.getGroup(@now.room)
  _gruop.hasClient onlineUsers[to], (bool) -> #判断用户是否在线,使用回调函数
    if bool
      self.now.receiveMessage "我对#{to}说:#{message}"
      nowjs.getClient onlineUsers[to], ->
        this.now.receiveMessage "#{self.now.username}对我说:#{message}"#重点:如何跟特定用户通信
    else
      self.now.receiveMessage "[ERR]#{to}不在这个房间!"

everyone.now.distributeMessage = (message) ->
  nowjs.getGroup(@now.room).now.receiveMessage(message);


chatroom.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>聊天室</title>
</head>
<script type="text/javascript" src="/jquery.js"></script>
<script src="/nowjs/now.js"></script>
<script src="/coffee-script.js"></script>
<script type="text/coffeescript">
    now.receiveMessage = (message) ->
        $("div#talkFrame").append "<br>"+ message

    $(document).ready ->
        $('#login').click ->
            if $('#userName').val() == ''
                alert 'please input user name!'
            else
                now.chckUser $('#userName').val(), (exist)-> #重点:使用回调函数,异步调用的方式。
                    if exist