HttpSession getAttribute() returning null - java

I'm trying to do a websocket communication with eclipse ide and when i run my code i get a NullPointerException. I've checked and the name in the getAttribute is the same as in the bean
package ws;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.server.ServerEndpoint;
import fundstarter.model.ConnectToRMIBean;
import javax.servlet.http.HttpSession;
import javax.websocket.*;
#ServerEndpoint(value="/ws", configurator = HandShake.class)
public class WebSocketAnnotation {
private Session session;
private ConnectToRMIBean sessionUser;
private HttpSession httpSession;
private static final Set<WebSocketAnnotation> myConnections = new CopyOnWriteArraySet<WebSocketAnnotation>();
public WebSocketAnnotation() {
}
#OnOpen
public void start(Session session, EndpointConfig config) {
this.session = session;
this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
myConnections.add(this);
this.sessionUser = (ConnectToRMIBean) httpSession.getAttribute("RMIBean");
//sendMessage("New message");
}
#OnClose
public void end() {
// clean up once the WebSocket connection is closed
myConnections.remove(this);
}
#OnMessage
public void receiveMessage(String message) {
sendMessage(message);
}
#OnError
public void handleError(Throwable t) {
t.printStackTrace();
}
private void sendMessage(String text) {
try {
System.out.println("[WebSocketAnnot]RMIBean User Id -> " + this.sessionUser.getUserID());
this.session.getBasicRemote().sendText(text);
} catch (IOException e) {
try {
this.session.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
Can anyone tell me what is my error?

I found the error. It was a typo on the modifyHandshake method on the HandShake

Related

Java Websocket Client as Servlet (App Engine)

I am trying to establish a WebSocket connection in my servlet. I receive some callback messages from the server, but only very few. I call a Thread.sleep(30000), so the servlet should wait 30 seconds for new messages, but it seems not wait for some reason.
This is the code in my Servlet:
try {
// open websocket
final WebsocketClientEndpoint clientEndPoint = new WebsocketClientEndpoint(new URI("wss://www.bitmex.com/realtime"));
// add listener
clientEndPoint.addMessageHandler(new WebsocketClientEndpoint.MessageHandler() {
public void handleMessage(String message) {
System.out.println(message);
logger.info("WEBSOCKET MSG: "+message);
}
});
// send message to websocket
clientEndPoint.sendMessage("{\"op\": \"subscribe\", \"args\": \"trade\"}");
// wait 30 seconds for messages from websocket
Thread.sleep(30000);
} catch (InterruptedException ex) {
System.err.println("InterruptedException exception: " + ex.getMessage());
} catch (URISyntaxException ex) {
System.err.println("URISyntaxException exception: " + ex.getMessage());
}
And this is my WebsocketClientEndpoint code:
import java.net.URI;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
#ClientEndpoint
public class WebsocketClientEndpoint {
Session userSession = null;
private MessageHandler messageHandler;
public WebsocketClientEndpoint(URI endpointURI) {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(this, endpointURI);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Callback hook for Connection open events.
*
* #param userSession the userSession which is opened.
*/
#OnOpen
public void onOpen(Session userSession) {
System.out.println("opening websocket");
this.userSession = userSession;
}
/**
* Callback hook for Connection close events.
*
* #param userSession the userSession which is getting closed.
* #param reason the reason for connection close
*/
#OnClose
public void onClose(Session userSession, CloseReason reason) {
System.out.println("closing websocket");
this.userSession = null;
}
/**
* Callback hook for Message Events. This method will be invoked when a client send a message.
*
* #param message The text message
*/
#OnMessage
public void onMessage(String message) {
if (this.messageHandler != null) {
this.messageHandler.handleMessage(message);
}
}
public void addMessageHandler(MessageHandler msgHandler) {
this.messageHandler = msgHandler;
}
public void sendMessage(String message) {
this.userSession.getAsyncRemote().sendText(message);
}
public static interface MessageHandler {
public void handleMessage(String message);
}
}
What's the right way to do it? Or could this be some issue with App Engine (Standard Environment)?

I am not able to connect to my websocket server through Java websocket client

I am not able to connect to my websocket server through Java websocket client.Please help!
Apache Tomcat 8.0.26 is being used
Getting exception as "java.io.IOException: An operation was attempted on something that is not a socket.
Client Class
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.concurrent.CountDownLatch;
import javax.websocket.*;
#ClientEndpoint
public class WebSocketClient {
private static Object waitLock = new Object();
protected Session userSession = null;
private MessageHandler messageHandler;
private static void wait4TerminateSignal() {
synchronized (waitLock) {
try {
waitLock.wait();
} catch (InterruptedException e) {
}
}
}
public void Connect(String sServer) throws InterruptedException {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
System.out.println("Connecting");
WebSocketClient webSocketClient = new WebSocketClient();
userSession = container.connectToServer(webSocketClient, URI.create(sServer));
wait4TerminateSignal();
System.out.println("Connected");
} catch (DeploymentException | IOException e) {
e.printStackTrace();
}
}
/**
* register message handler
*
* #param message
*/
public void addMessageHandler(MessageHandler msgHandler) {
this.messageHandler = msgHandler;
}
/**
* Send a message.
*
* #param user
* #param message
*/
public void sendMessage(String message) {
this.userSession.getAsyncRemote().sendText(message);
}
public void SendMessage(String sMsg) throws IOException {
userSession.getBasicRemote().sendText(sMsg);
}
#OnOpen
public void onOpen(Session session) {
System.out.println("Connected");
}
#OnClose
public void onClose(Session session, CloseReason closeReason) {
}
#OnMessage
public void onMessage(Session session, String msg) {
System.out.println(msg);
}
public void Disconnect() throws IOException {
userSession.close();
}
}

Close websocket connection with Java

How to close a websocket connection using Java WebSocket API? I have used Java websocket API for both server and client end points. The application is working fine. But I don't know how to close the websocket, before the main thread ends.
This is my ClientEndpoint
package websocket.client;
import java.io.IOException;
import javax.websocket.MessageHandler;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
#ClientEndpoint
public class EchoClient {
Session session;
//request
#OnOpen
public void onOpen(Session session, EndpointConfig config) {
System.out.println("Connected to endpoint: " + session.getBasicRemote());
this.session = session;
sendMessage("Welcome to WebSocket");
}
//response
#OnMessage
public void onMessage(String text) {
System.out.println("Received response in client from server: " + text);
}
#OnError
public void onError(Session session, Throwable t) {
t.printStackTrace();
}
private void sendMessage(String message) {
System.out.println("Sending message from client to server: " + message);
System.out.println(session);
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
And I use the following code to start the ClientEndPoint
import java.io.IOException;
import java.net.URI;
import javax.websocket.ContainerProvider;
import javax.websocket.DeploymentException;
import javax.websocket.WebSocketContainer;
import websocket.client.EchoClient;
public class WebSocketDemo {
public static void main(String[] args) {
String uri = "ws://localhost:8080/websocket";
System.out.println("Connecting to " + uri);
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
try {
container.connectToServer(EchoClient.class, URI.create(uri));
} catch (DeploymentException | IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
PS : I haven't used JavaScript.
The WebSocketContainer's connectToServer method returns websocket Session object that has two close methods. That should do the trick.

Tomcat WebSocket connection closed, Code: 1006 issue

I'm trying Tomcat server with websocket. This is what I do:
I created 3 java files, copied from Tomcat examples. Please see the code below.
Then I build a war file and put it in webapps. But then I got this error message:
Info: WebSocket connection closed, Code: 1006
Do I miss any step to make a websocket on Tomcat?
Thanks.
1. ExamplesConfig.java
import java.util.HashSet;
import java.util.Set;
import javax.websocket.Endpoint;
import javax.websocket.server.ServerApplicationConfig;
import javax.websocket.server.ServerEndpointConfig;
public class ExamplesConfig implements ServerApplicationConfig
{
#Override
public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> scanned)
{
Set<ServerEndpointConfig> result = new HashSet<ServerEndpointConfig>();
System.out.println("ExamplesConfig ==========> getEndpointConfigs");
if (scanned.contains(EchoEndpoint.class))
{
result.add(ServerEndpointConfig.Builder.create(EchoEndpoint.class, "/websocket/echoProgrammatic").build());
}
return result;
}
#Override
public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scanned)
{
// Deploy all WebSocket endpoints defined by annotations in the examples
// web application. Filter out all others to avoid issues when running
// tests on Gump
Set<Class<?>> results = new HashSet<Class<?>>();
for (Class<?> clazz : scanned)
{
if (clazz.getPackage().getName().startsWith("websocket."))
{
System.out.println("getAnnotatedEndpointClasses ===========>" + clazz);
results.add(clazz);
}
}
return results;
}
}
2. EchoEndpoint.java
import java.io.IOException;
import java.nio.ByteBuffer;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.MessageHandler;
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
public class EchoEndpoint extends Endpoint
{
#Override
public void onOpen(Session session, EndpointConfig endpointConfig) {
RemoteEndpoint.Basic remoteEndpointBasic = session.getBasicRemote();
session.addMessageHandler(new EchoMessageHandlerText(remoteEndpointBasic));
session.addMessageHandler(new EchoMessageHandlerBinary(remoteEndpointBasic));
}
private static class EchoMessageHandlerText
implements MessageHandler.Partial<String> {
private final RemoteEndpoint.Basic remoteEndpointBasic;
private EchoMessageHandlerText(RemoteEndpoint.Basic remoteEndpointBasic) {
this.remoteEndpointBasic = remoteEndpointBasic;
}
#Override
public void onMessage(String message, boolean last) {
try {
if (remoteEndpointBasic != null) {
remoteEndpointBasic.sendText(message, last);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static class EchoMessageHandlerBinary
implements MessageHandler.Partial<ByteBuffer> {
private final RemoteEndpoint.Basic remoteEndpointBasic;
private EchoMessageHandlerBinary(RemoteEndpoint.Basic remoteEndpointBasic) {
this.remoteEndpointBasic = remoteEndpointBasic;
}
#Override
public void onMessage(ByteBuffer message, boolean last) {
try {
if (remoteEndpointBasic != null) {
remoteEndpointBasic.sendBinary(message, last);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
3. EchoAnnotation.java
import java.io.IOException;
import java.nio.ByteBuffer;
import javax.websocket.OnMessage;
import javax.websocket.PongMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/websocket/echoAnnotation")
public class EchoAnnotation
{
#OnMessage
public void echoTextMessage(Session session, String msg, boolean last) {
try {
if (session.isOpen()) {
System.out.println("==========> this is my code");
session.getBasicRemote().sendText(msg, last);
}
} catch (IOException e) {
try {
session.close();
} catch (IOException e1) {
// Ignore
}
}
}
#OnMessage
public void echoBinaryMessage(Session session, ByteBuffer bb,
boolean last) {
try {
if (session.isOpen()) {
session.getBasicRemote().sendBinary(bb, last);
}
} catch (IOException e) {
try {
session.close();
} catch (IOException e1) {
// Ignore
}
}
}
/**
* Process a received pong. This is a NO-OP.
*
* #param pm Ignored.
*/
#OnMessage
public void echoPongMessage(PongMessage pm) {
// NO-OP
}
}
This example work's fine with Tomcat 7.0.x if you are running JVM version 1.7 and your web.xml use Servlet Specification version 3.0 according to Tomcat documentation.
You web.xml file should look like this :
<web-app version="3.0" ... >

send multiple messages using web socket server end point in java api

I am trying to implement Java WebSocket api.
I am using this example for implementation.
My Client End Point Code is as below:
package com.java.webSocket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.DeploymentException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import org.glassfish.tyrus.client.ClientManager;
#ClientEndpoint
public class WordgameClientEndpoint {
private static CountDownLatch latch;
#OnOpen
public void onOpen(Session session) {
System.out.println("Connected ... " + session.getId());
}
#OnMessage
public String onMessage(String message, Session session) {
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("session.getId():-- " + session.getId());
System.out.println("Received ...." + message);
String userInput = bufferRead.readLine();
return userInput;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
#OnClose
public void onClose(Session session, CloseReason closeReason) {
System.out.println(String.format("Session %s close because of %s", session.getId(), closeReason));
latch.countDown();
}
public static void main(String[] args) {
latch = new CountDownLatch(1);
ClientManager client = ClientManager.createClient();
try {
client.connectToServer(WordgameClientEndpoint.class, new URI("ws://localhost:8182/WbSocketDemoTest/game"));
latch.await();
} catch (DeploymentException | URISyntaxException | InterruptedException e) {
throw new RuntimeException(e);
}
}
}
WebSocketServer.java is as below:
package com.java.webSocket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.glassfish.tyrus.server.Server;
public class WebSocketServer {
public static void main(String[] args) {
runServer();
}
public static void runServer() {
Server server = new Server("localhost", 8182, "/WbSocketDemoTest", WordgameServerEndpoint.class);
try {
server.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please press a key to stop the server.");
reader.readLine();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
server.stop();
}
}
}
My Server End points code is as below:
package com.java.webSocket;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.CloseReason;
import javax.websocket.CloseReason.CloseCodes;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint(value = "/game")
public class WordgameServerEndpoint {
private static final Set<WordgameServerEndpoint> connections = new CopyOnWriteArraySet<WordgameServerEndpoint>();
//private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());
private Session session;
#OnOpen
public void onOpen(Session session) {
System.out.println("Connected ... " + session.getId());
this.session = session;
connections.add(this);
try {
session.getBasicRemote().sendText("message form onOpen of server");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#OnMessage
public void onMessage(String message, Session session) throws IOException {
switch (message) {
case "quit":
try {
session.close(new CloseReason(CloseCodes.NORMAL_CLOSURE,
"Game ended"));
} catch (IOException e) {
throw new RuntimeException(e);
}
break;
}
broadcast2(session,message);
}
private void broadcast2(Session currentSession, String message){
for(WordgameServerEndpoint current : connections){
try {
System.out.println("in broadcast current.session.getId():-- " + current.session.getId());
current.session.getBasicRemote().sendText(message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#OnClose
public void onClose(Session session, CloseReason closeReason) {
System.out.println(String.format("Session %s closed because of %s",
session.getId(), closeReason));
}
}
The problem is in broadcast2(Session currentSession, String message) method.
It shows all connected clients but sends message to only one client instead of all.
I want to implement this in spring, so any suggestion is highly appreciated.

Categories

Resources