Hello!

Yesterday I suffered with these web-sites, they did not want to work. When I ran tomcat through IDEA, I had to download TomEE, it seems to work in it. This resulted in the following server:

@ServerEndpoint("/websocket/chat") public class Chat { private String username = null; @OnOpen public void onOpen(Session session) { } @OnMessage public void sendMessage(Session session, String msg) { JSONObject incoming = new JSONObject(msg); if (incoming.has("username")) { username = incoming.getString("username"); } if (incoming.has("text")) { String text = incoming.getString("text"); for (Session ss : session.getOpenSessions()) { try { if (ss.isOpen()) { ss.getBasicRemote().sendText(username + ": " + text); } } catch (IOException e) { try { ss.close(); } catch (IOException ignored) { } } } } } } 

Well, everything seems to be clear here, JSON strings come, if there is a name in it (it is sent when connected), remember the name, if the text variable, send this text to all open sessions.

Experienced to establish that an object of class Chat (by the way, how correctly is the @ServerEndpoint class called? ) Is created for each new connection and exists all the time while the connection is active.

But the question is: how to tie it now to my main server, well, there, through normal sockets or through RMI?

For what it is necessary: let's say, I want to establish a chat between two users. They connect, send their username / password to @OnMessage, say, through RMI, the Authorize method is called (String login, String pass, int sessionId), and somewhere in the memory of the sessionId server is associated with a specific user. What now needs to be done so that when the user receives a message (an event on the server), it is sent to the client?

PS While I was writing, I had the idea to transfer to the server via RMI the Session object, the correct idea?

PPS A lot of the text turned out, sorry. Maybe my question will be useful to someone else.

    1 answer 1

    I came up with such a thing:

     @ServerEndpoint("/websocket/chat") public class Chat { private static MainProcessor processor = null; @OnOpen public void onOpen(Session session) { if (processor == null) { processor = new MainProcessor(); } } @OnMessage public void sendMessage(Session session, String msg) { ... } } 

    At the first connection, we create an object of the class MainProcessor and do everything in it that our heart desires.