我正在尝试仅针对服务器和客户端(不允许使用Javascript)以及WebSocket使用JavaEE构建基于JavaEE网络的聊天应用程序。
我已经成功建立了到服务器的连接(借助于网上的教程),但是,在发送消息时,什么也没有发生,换句话说,OnMessage方法没有触发。作为WebSockets的新手,我不能为做错的事情而烦恼。
这是代码
服务器
import static java.lang.String.format;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.websocket.EncodeException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import server.MessageDecoder;
import server.MessageEncoder;
import entities.ApplicationUser;
import entities.Message;
@javax.websocket.server.ServerEndpoint(value = "/chat", encoders = MessageEncoder.class, decoders = MessageDecoder.class)
public class ServerEndpoint {
static Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());
@OnOpen
public void onOpen(Session session) {
System.out.println(format("%s joined the chat room.", session.getId()));
sessions.add(session);
}
@OnMessage
public synchronized void onMessage(Session session, Message message) throws IOException, EncodeException {
System.out.println("Here i am 0 ");
ApplicationUser user = (ApplicationUser) session.getUserProperties().get("userSender");
if (user == null) {
session.getUserProperties().put("userSender", message.getSender());
session.getUserProperties().put("userReceiver", message.getReceiver());
}
System.out.println("Here i am 1 ");
System.out.println(format("[%s:%s] %s", session.getId(), message.getDateSent(), message.getMessage()));
System.out.println("Here i am 2 ");
sendMessageToOne(message, session, message.getReceiver().getSessionId());
}
public void sendMessageToOne(Message message, Session session, String strToSessionId) {
for (Session s : sessions) {
if (s.isOpen()) {
try {
if (s.getId().equals(strToSessionId))
try {
System.out.println("Here i am 3 ");
s.getBasicRemote().sendObject(message);
System.out.println("Here i am 4 ");
} catch (EncodeException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@OnClose
public void onClose(Session session) throws IOException, EncodeException {
System.out.println(format("%s left the chat room.", session.getId()));
sessions.remove(session);
// notify peers about leaving the chat room
for (Session peer : sessions) {
Message chatMessage = new Message();
//chatMessage.setSender("Server");
//chatMessage.setContent(format("%s left the chat room.", (String) session.getUserProperties().get("user")));
//chatMessage.setReceived(new Date());
peer.getBasicRemote().sendObject(chatMessage);
}
}
}
消息编码器
import util.JsonUtil;
import Message;
import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;
public class MessageEncoder implements Encoder.Text<Message> {
@Override
public void init(final EndpointConfig config) {
}
@Override
public void destroy() {
}
@Override
public String encode(final Message message) throws EncodeException {
return JsonUtil.formatMessage(message);
}
}
消息解码器
import javax.json.Json;
import javax.json.JsonObject;
import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;
import org.joda.time.DateTime;
import entities.ApplicationUser;
import entities.Message;
import java.io.StringReader;
public class MessageDecoder implements Decoder.Text<Message> {
@Override
public void init(final EndpointConfig config) {
}
@Override
public void destroy() {
}
@Override
public Message decode(final String textMessage) throws DecodeException {
Message chatMessage = new Message();
JsonObject obj = Json.createReader(new StringReader(textMessage))
.readObject();
chatMessage.setMessage(obj.getString("message"));
chatMessage.setSender(new ApplicationUser(Integer.parseInt(obj.getJsonObject("sender").getString("id")),
obj.getJsonObject("sender").getString("email"),
obj.getJsonObject("sender").getString("username")));
chatMessage.setDateSent(new DateTime());
return chatMessage;
}
@Override
public boolean willDecode(final String s) {
return true;
}
}
客户端
import static java.lang.String.format;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import java.text.SimpleDateFormat;
import server.MessageDecoder;
import server.MessageEncoder;
import entities.Message;
@javax.websocket.ClientEndpoint(encoders = MessageEncoder.class, decoders = MessageDecoder.class)
public class ClientEndpoint {
private SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
@OnOpen
public void onOpen(Session session) {
System.out.println(format("Connection established. session id: %s", session.getId()));
}
@OnMessage
public void onMessage(Message message) {
System.out.println("Client " + format("[%s:%s] %s", simpleDateFormat.format(message.getDateSent()), message.getSender(), message.getMessage()));
}
}
选择用户与之聊天时在其中创建服务器的ChatBean
public String doGet(int destinationUserId) {
System.out.println("Chat.doGet()");
for (ApplicationUser user : userBean.getAllUsers()) {
if(user.getId() == destinationUserId)
{
this.receiver = user;
break;
}
}
// Start the server
org.glassfish.tyrus.server.Server server = new org.glassfish.tyrus.server.Server("localhost", 8025, "/ws", ServerEndpoint.class);
try {
server.start();
System.out.println("I am here Right Now ");
} catch (DeploymentException e) {
throw new RuntimeException(e);
} finally {
//server.stop();
}
String roomName = Integer.toString(loginBean.getUser().getId()) + "0" + Integer.toString(destinationUserId);
ClientManager client = ClientManager.createClient();
//String message;
// connect to server
System.out.println("Welcome to Our Chat App!");
try {
session = client.connectToServer(ClientEndpoint.class, new URI(SERVER));
// Set the user's session id
loginBean.getUser().setSessionId(session.getId());
} catch (DeploymentException | URISyntaxException e1) {
e1.printStackTrace();
}
System.out.println("You are logged in as: " + session.getUserProperties().get("userSender"));
return displayChatThreads();
}
public String displayChatThreads() {
return "/template/chat/chat.xhtml/?faces-redirect=true";
}
单击“发送消息”按钮时调用的操作
public String doPost() {
System.out.println("Chat.doPost()");
System.out.println("Server ");
// Send first message
System.out.println("Here I am now 1 ");
handleSendMessage();
return displayChatThreads();
}
private void handleSendMessage() {
System.out.println("Message Sent " + msg);
Message textMessage = new Message(msg, loginBean.getUser(), receiver, new DateTime(DateTime.now()));
try {
session.getBasicRemote().sendText(JsonUtil.formatMessage(textMessage));
System.out.println("Message Sent " + session);
} catch (IOException e) {
e.printStackTrace();
}
}