Hướng Dẫn Thêm Tính Năng Chat Vào Ezyfox Server - Phần 2
Ở bài viết trước, chúng ta đã làm quen với Ezyfox Server thông qua một ứng dụng nhỏ sử dụng giao thức WS. Trong ứng dụng này, client sẽ thực hiện các bước HANDSHAKE
và LOGIN
, nhận một lời chào từ backend server, và hiển thị lời chào đó trên trang web. Hôm nay, chúng ta sẽ tiếp tục phát triển ứng dụng của mình bằng cách thêm tính năng chat thời gian thực giữa hai người dùng.
Video Demo (1 phút):
[Link tới Video Demo]
Code Mẫu:
Để tìm hiểu chi tiết về mã nguồn, bạn có thể xem ở đây và đây. Giờ, chúng ta hãy bắt đầu nhé!
Các bước Thêm Tính Năng Chat
1. Gọi Lệnh active-users
và Xử Lý Phản Hồi Từ Ezy Server
Để người dùng có thể chat với nhau, ứng dụng cần hiển thị danh sách các người dùng đang trực tuyến trong hệ thống. Người dùng có thể chọn một ai đó để bắt đầu cuộc trò chuyện. Để thực hiện điều này, client sẽ gọi lệnh active-users
tới server và server sẽ trả về danh sách người dùng đang trực tuyến.
javascript
setupApp.addDataHandler("greet", function (app, data) {
var message = data.message;
alert(message);
$('.connect').remove();
app.sendRequest('active-users', {});
setInterval(function () {
app.sendRequest('active-users', {});
}, 1000);
});
setupApp.addDataHandler("active-users", function (app, data) {
getAllActiveUser(data, app);
setupClickOnAPersonAndSendBtn(app);
});
function getAllActiveUser(data, app) {
var activeUsers = data['active-users'].filter(e => e.id !== app.client.me.id);
var bigS = $('#result-panel');
bigS.removeAttr("hidden");
var onlineList = bigS.find('.list-group');
onlineList.empty();
activeUsers.forEach(e => {
onlineList.append('<li><a data-username="' + e.name + '" class="list-group-item" id="' + e.id + '" href="javascript:void(0);">' + e.name + '<span hidden class="badge">!</span></a></li>')
});
}
2. Thiết lập Xử lý Click và Nút Gửi Tin Nhắn
Khi người dùng bấm vào một ai đó để bắt đầu chat, ứng dụng sẽ hiển thị khung chat và thiết lập nút gửi tin nhắn.
javascript
function setupClickOnAPersonAndSendBtn(app) {
var bigChat = $('#chat-window-1');
$('.list-group-item').on("click", function (object) {
bigChat.removeAttr('hidden');
var panelBody = bigChat.find('.panel-body');
panelBody.children().not(':first').remove();
var thiz = $(this);
var id = thiz.attr('id');
var name = thiz.attr('data-username');
bigChat.find('#chat-title').text('Chat với ' + name);
var btnChat = bigChat.find('#btn-chat');
btnChat.attr('data-user-id', id);
bigChat.attr('data-user-id', id);
btnChat.off('click');
btnChat.on('click', function () {
var msg = bigChat.find('#btn-input').val();
if (msg && msg.length > 0) {
app.sendRequest('chat', {from: app.client.me.id, to: +id, content: msg});
var msgDiv =
'<div class="row msg_container base_sent">' +
' <div class="col-md-10 col-xs-10">' +
' <div class="messages msg_sent">' +
' <p>' + msg + '</p>' +
' </div>' +
' </div>' +
' <div class="col-md-2 col-xs-2 avatar">' +
' <img src="avatar_link_placeholder" class=" img-responsive ">' +
' </div>' +
'</div>';
panelBody.append(msgDiv);
}
});
});
}
3. Xử lý Lệnh chat
Từ Client Gửi Lên Server
Khi server nhận được lệnh chat
, nó sẽ gửi tin nhắn đến đúng người nhận dựa trên ID người gửi và người nhận.
java
@EzyRequestController
@Setter
public class ChatRequestHandler extends EzyLoggable {
@EzyAutoBind("appResponseFactory")
protected EzyResponseFactory responseFactory;
@EzyDoHandle("chat")
public void secureChat(EzyUser user, EzyAppContext appContext, ChatRequest request) {
responseFactory.newObjectResponse()
.encrypted()
.command("chat")
.param("chat", new ChatResponse(request))
.user(appContext.getApp().getUserManager().getUser(request.getTo()))
.execute();
}
}
Tóm Tắt
Chúng ta đã xây dựng một ứng dụng chat thời gian thực đơn giản với Ezyfox Server, bao gồm tính năng hiển thị người dùng trực tuyến và gửi nhận tin nhắn. Trong các bài viết sau, chúng ta sẽ tìm hiểu thêm về các tính năng nâng cao như lưu trữ tin nhắn cũ và thông báo tin nhắn mới. Cám ơn bạn đã theo dõi!
Hy vọng bài viết này sẽ giúp ích cho bạn trong việc phát triển ứng dụng chat của mình.
source: viblo