0

I'm using the javax.websocket API in Java. I am using a Jetty server and Javascript for the client. How do I initiate sendMessage from the server?

Details: Am using a jetty-maven-plugin 9.4.8.v20171121.

Server-side dependencies: org.eclipse.jetty.websocket - websocket-server and javax-websocket-server-impl.

Here's my server code:

package com.trice.server.web;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/WebSocketTestServlet")
public class WebSocketTestServlet {
 @OnOpen
 public void onOpen(){
 System.out.println("Open Connection ...");
 }
 @OnClose
 public void onClose(){
 System.out.println("Close Connection ...");
 }
 @OnMessage
 public String onMessage(String message){
 System.out.println("Message from the client: " + message);
 String echoMsg = "Echo from the server : " + message;
 return echoMsg;
 }
 @OnError
 public void onError(Throwable e){
 e.printStackTrace();
 }
}

And client code:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tomcat WebSocket</title>
</head>
<body>
 <form>
 <input id="message" type="text">
 <input onclick="wsSendMessage();" value="Echo" type="button">
 <input onclick="wsCloseConnection();" value="Disconnect" type="button">
 </form>
 <br>
 <textarea id="echoText" rows="5" cols="30"></textarea>
 <script type="text/javascript">
 var webSocket = new WebSocket("ws://localhost:8080/WebSocketTestServlet");
 var echoText = document.getElementById("echoText");
 echoText.value = "";
 var message = document.getElementById("message");
 webSocket.onopen = function(message){ wsOpen(message);};
 webSocket.onmessage = function(message){ wsGetMessage(message);};
 webSocket.onclose = function(message){ wsClose(message);};
 webSocket.onerror = function(message){ wsError(message);};
 function wsOpen(message){
 echoText.value += "Connected ... \n";
 }
 function wsSendMessage(){
 webSocket.send(message.value);
 echoText.value += "Message sent to the server : " + message.value + "\n";
 message.value = "";
 }
 function wsCloseConnection(){
 webSocket.close();
 }
 function wsGetMessage(message){
 echoText.value += "Message received from to the server : " + message.data + "\n";
 }
 function wsClose(message){
 echoText.value += "Disconnect ... \n";
 console.log("disconnect", message);
 }
 function wsError(message){
 echoText.value += "Error \n";
 console.log("error", message);
 }
 </script>
</body>
</html>

Reference link

Appreciate any help. Thanks.

asked Jan 4, 2018 at 10:49
6
  • Your question misses some information: on what condition do you want to send a message? Upon another message received? Upon an event? Anyway, for a basic answer, a link to a tutorial (section 4.4) will do: session.getBasicRemote().sendText("yahooo!"); Commented Jan 7, 2018 at 22:21
  • I wanted to send a message when an event occurred. Commented Jan 8, 2018 at 6:06
  • 1
    As per your answer, it was a simple stuff... By the way, if you plan to use CDI events (@Observes) in your ServerEndpoint, please be aware that if no websocket client is connected, you may encounter some issues. In my project, we use a session handler class to handle CDI events Commented Jan 8, 2018 at 9:04
  • In my limited experience, I haven't come across CDI events...can you please elaborate? Any specific examples that can throw some light on the matter will be great...Thanks Commented Jan 8, 2018 at 10:01
  • If you're free, I'll rather talk in a chat: chat.stackoverflow.com/rooms/162727/… (I'm new to chat...) Commented Jan 8, 2018 at 10:08

1 Answer 1

1

There was a very easy answer to my question. All I needed to do was:

session.getBasicRemote().sendText("Some string");
answered Jan 8, 2018 at 6:08
Sign up to request clarification or add additional context in comments.

4 Comments

How do you get the session object?? @raksheetbhat
Define a websocket ServerEndpoint which defines callback methods - @OnOpen public void onOpen(Session wsSession, @PathParam("param") final String param) which gives you a websocket.session object.
I had looked at the article previously. In that sending of a message to user 2 is initiated by receiving of a message from user 2. So it's not purely initiated from server side. In my case, it's like after completion of asynchronous batch job, i need to send a message to the browser. In this case how can we get the session?
You can maintain a list of user sessions server side, and retrieve those sessions when you need to send a message to all active users. Or maintain a hashmap with userid, so you can retrieve sessions for particular users.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.