我创建了一个spring boot应用程序,它包含控制器和websocket配置。为了测试,我在同一个应用程序中创建了html和angularjs文件。
如果有2个不同的用户登录..他们可以聊天。工作正常。
我使用spring创建一个Web应用程序并添加html和angularjs页面。因此,一个用户登录Web应用程序页面,另一个用户通过以前的应用程序登录(测试)并尝试聊天。
Web应用程序中的用户无法接收任何消息,这意味着用户通过测试页面可以接收消息。
我的示例代码:
package com.aghil.chat.controller;
import java.security.Principal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import com.aghil.chat.dto.ChatMessageDto;
@Controller
public class ChatMessageController {
@Autowired
SimpMessagingTemplate template;
@MessageMapping("/chat")
public void greeting(Message<Object> message, @Payload ChatMessageDto chatMessage) throws Exception {
System.out.println("Stomp client called");
Principal principal = message.getHeaders().get(SimpMessageHeaderAccessor.USER_HEADER, Principal.class);
String authedSender = principal.getName();
chatMessage.setSender(authedSender);
String recipient = chatMessage.getRecipient();
System.out.println("authedSender : "+authedSender +" --- recipient :: "+recipient);
if (!authedSender.equals(recipient)) {
template.convertAndSendToUser(authedSender, "/queue/messages", chatMessage);
}
template.convertAndSendToUser(recipient, "/queue/messages", chatMessage);
}
}
JS:
function connect() {
var socket = new SockJS('/chat');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/user/queue/messages', function(greeting){
showMessage(greeting.body);
});
});
}
function sendMessage() {
var recipient = document.getElementById('recipient').value;
var message = document.getElementById('message').value;
var date = new Date();
var time = date.toISOString();
stompClient.send("/app/chat", {}, JSON.stringify({ 'sender': '', 'recipient': recipient, 'message': message, 'time': time }));
}
function showMessage(message) {
var jsonResponse = JSON.parse(message);
var response = document.getElementById('response');
if(jsonResponse.message !== "New Chat Request") {
var eachMgsDiv = document.createElement('div');
eachMgsDiv.setAttribute('class','col-sm-12 ng-scope');
var recipient = document.getElementById('recipient').value;
if(jsonResponse.recipient === recipient) {
eachMgsDiv.innerHTML = myMgsTmpPrt1 + jsonResponse.sender + myMgsTmpPrt2 + myMgsTmpPrt3 + jsonResponse.message + myMgsTmpPrt4 + new Date(jsonResponse.time) + myMgsTmpPrt5;
}
else {
eachMgsDiv.innerHTML = othersMgsTmpPrt1 + jsonResponse.sender + othersMgsTmpPrt2 + othersMgsTmpPrt3 + jsonResponse.message + othersMgsTmpPrt4 + new Date(jsonResponse.time) + othersMgsTmpPrt5;
}
response.appendChild(eachMgsDiv);
}