NodeJS + Socket.io搭建聊天服务器

第一步:安装node

git clone https://github.com/joyent/node.git

cd node

git checkout v0.10.33-release

./configure

make

make install

 

第二步:安装npm

     mac下使用命令ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

第三步:安装redis

wget http://download.redis.io/releases/redis-2.8.17.tar.gz

cd redis-2.8.17

make

启动redis服务

src/redis-server

 

第四步:创建package.json

cd /data/project/current/

npm init

name: (20141201051425) chat-server

version: (1.0.0)

description: chat nodejs socket.io

entry point: (chat_server.js)

test command: chat-server

git repository: (https://github.com/monstar-lab/maturi.git)

keywords: chat nodejs socket.io

author: project

license: (ISC)

 

第五步:

npm install redis --save

npm install socket.io --save

npm install socket.io-redis --save

npm install fs --save

 

其他
==========================================
npm install -g node-gyp
npm install -g npm
npm install nan -save
cd node-posix
node-gyp configure
node-gyp build
 
var posix = require('node-posix’);
posix.setrlimit('nofile', { soft: 10000, hard: 10000 });
================================================
npm uninstall xxx -save
 
 
 
1
2
// これで通信中のIDが取得できる
var id = socket.id

メッセージを送信してきたClientへメッセージを返答

1
socket.emit('message', info);

接続しているClient全体にメッセージを送信

1
io.sockets.emit('message', info);

個別にデータを送信

1
io.sockets.socket(socket.id).emit('message', info);
  • socket.emit('message','the message to be transmitted'); //simple transmission
  • io.sockets.emit('message',"the message to be transmitted"); //send to all clients
  • socket.broadcast.emit('message',"this is a test"); //send to all except sender

Joining and leaving

You can call join to subscribe the socket to a given channel:

io.on('connection', function(socket){
  socket.join('some room');
});

And then simply use to or in (they are the same) when broadcasting or emitting:

io.to('some room').emit('some event'):

 
To leave a channel you call leave in the same fashion as join.
 
var sockets = io.sockets.sockets;
 
 
io.sockets.on('connection', function(socket){
//console.log('コネクション数',socket.client.conn.server.clientsCount);

    process.setMaxListeners(0);
   
    process.on('uncaughtException', function (err) {
        //打印出错误
        console.log('uncaughtException: ');
        console.log(err);
        //打印出错误的调用栈方便调试
        console.log(err.stack);
      });
})
 
socket连接数太少
sudo prlimit --nofile=10240  --pid 16728
pid修改成node的pid
lsof -i:8000
 
设定sudo prlimit --nofile=10240  --pid 16728
查看sudo prlimit --nofile  --pid node的pid
 
 
netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'
 ps H -eo user,pid,ppid,tid,time,%cpu,cmd --sort=%cpu
lsof -i:8000
lsof | grep TCP | grep 8000 | grep ESTABLISHED | wc -l
ps -e -o 'pid,comm,args,pcpu,rsz,vsz,stime,user,uid' | grep node |  sort
netstat –apn | grep 8000
 
pgrep -l node 
posted @ 2015-07-23 13:34  Adtuu  阅读(568)  评论(0编辑  收藏  举报