第一步:安装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
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'):
leave
in the same fashion as join
.//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);