2012-03-13 6 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

+0

감사합니다. 나는 서버를 만들 수 있습니다. 초보자로서 모든 클라이언트에게 메시지를 브로드 캐스팅하기 때문에 클라이언트 서버 통신을 통해 개인 채팅을하는 방법을 혼란스럽게 생각합니다. –

답변

4

두 가지 방법이 있습니다 :

현재 내가 서버에이 코드를 얻었다. Thirst는 배열의 모든 소켓 (적어도 이들 소켓의 ID)에 대한 참조를 보유 할 수 있습니다. 사용자가 비공개 메시지를 내보낼 때 배열에서 대상 소켓을 검색하고이 특정 소켓으로 보내십시오. 소켓의 ID를 가지고 있어야합니다. 내부 번호 socket.id을 사용할 수 있지만 클라이언트가 다시 연결될 때 문제가 발생합니다 (새 ID 생성됨). 그리고 앱이 하나 이상의 컴퓨터에서 작동 할 때 (연결된 클라이언트 배열을 공유 할 수없는 경우) 다른 문제가 있습니다.

두 번째 방법은 방을 사용하는 것입니다. 클라이언트가 연결될 때마다 나는 그가 John이라는 이름을 가지고 있다고 가정합니다. 그런 다음 자신의 연결을 위해이 같은 것을 사용할 수 있습니다

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

지금이 방을 만든 다음 socket을 추가합니다. 당신이 요한에게 메시지를 보낼 경우에 당신은 단순히 당신이 메시지가 /priv/John 방에 소켓에 ​​정확히 갔다 확신 할 수 있습니다 그 시점에서

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

를 사용합니다. 이것은 을 socket.io (많은 기계 문제를 피하기 위해)와 세션 인증과 결합하여 완벽하게 작동합니다. 나는 memoryStore로 시도하지 않았지만 잘 작동 할 것입니다.

또한 고객이 연결을 끊을 때 객실에 대해 걱정할 필요가 없습니다. Socket.io는 자동으로 빈 방을 파괴합니다.

관련 문제