2012-03-13 107 views
3

我想使用php在nodeJs + MYSQL中構建一個聊天系統。這將是一對一的私人聊天,並將在數據庫中保存聊天。任何人都知道我需要從哪裏開始。Nodejs使用php的私人聊天

目前我得到的服務器驗證碼:

var app = require('express').createServer() 
var io = require('socket.io').listen(app); 

app.listen(8181); 

// routing 
app.get('/', function (req, res) { 
res.sendfile(__dirname + '/index.html'); 
}); 

// usernames which are currently connected to the chat 
var usernames = {}; 

io.sockets.on('connection', function (socket) { 

// when the client emits 'sendchat', this listens and executes 
socket.on('sendchat', function (data) { 
    // we tell the client to execute 'updatechat' with 2 parameters 
    io.sockets.emit('updatechat', socket.username, data); 
}); 

// when the client emits 'adduser', this listens and executes 
socket.on('adduser', function(username){ 
    // we store the username in the socket session for this client 
    socket.username = username; 
    // add the client's username to the global list 
    usernames[username] = username; 
    // echo to client they've connected 
    socket.emit('updatechat', 'SERVER', 'you have connected'); 
    // echo globally (all clients) that a person has connected 
    socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected'); 
    // update the list of users in chat, client-side 
    io.sockets.emit('updateusers', usernames); 
}); 

// when the user disconnects.. perform this 
socket.on('disconnect', function(){ 
    // remove the username from global usernames list 
    delete usernames[socket.username]; 
    // update list of users in chat, client-side 
    io.sockets.emit('updateusers', usernames); 
    // echo globally that this client has left 
    socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has   disconnected'); 
}); 
    }) 
+0

你究竟需要什麼?你已經知道如何編寫一個服務器。你在實現客戶端方面有問題嗎? – freakish 2012-03-13 07:59:30

+0

感謝feakish參與,我可以建立服務器,作爲初學者我很困惑如何使客戶端服務器通信實現私人聊天,因爲連接正在向所有客戶端廣播消息。 – 2012-03-13 08:04:31

回答

4

有兩種方法。渴望持有對數組中所有套接字的引用(至少都是這些套接字的ID)。當用戶發出私人消息時,您會搜索陣列中的目標套接字並將其發送給此特定套接字。這需要保存某種套接字的ID。您可以使用內部socket.id,但當客戶端重新連接時(新生成的ID),將會出現問題。而當你的應用在多臺機器上工作時(他們不能共享連接客戶機的陣列),還有另一個問題。

第二種方法是使用房間。每當客戶連接,我想他有一個名字,例如約翰。然後你可以使用這樣的事情對他的連接:

socket.join('/priv/'+name); 

現在,這創造了一個房間,並增加了socket它。如果你想發送消息給約翰,你只需使用

io.sockets.in('/priv/John').emit('msg', data); 

在這一點上,你可以肯定的是,消息正好去到插座中/priv/John房間。這與Redis結合socket.io(以避免許多機器問題)和會話授權完美配合。我沒有用memoryStore嘗試它,但它應該也可以。

當客戶斷開連接時,您也不用擔心房間。 Socket.io會自動銷燬空房間。