Hello I try many hours to get the Websocket API from Jetty with Sessions running.
My Problem is that, i can't interact externally with the Session, to send Data.
I can only interact to all Sessions and not only to one.
I tried to use the "Sec-WebSocket-Key" as Session Key, but it always returns java.lang.NullPointerException as the onWebSocketError.
I already tried to save the Session in a HashMap but every time, when i like to execute a sendString the Session in the HashMap is NULL.
My Code:
Connect Method
#Override
public void onWebSocketConnect(Session sessionIO) {
sessionIO.setIdleTimeout(Integer.MAX_VALUE);
System.out.print(gsonIO.toJson(this.getSession().getUpgradeResponse().getHeaders()));
sessionsIO.add(sessionIO);
loggerIO.log(LogType.SOCKET, "New Socket Connection from Client " + sessionIO.getRemoteAddress() + " with Sesssion ID: " + sessionIO.getPolicy().getBehavior().name() + ".");
}
My Function where i try to fetch my Session out of the Array
public static Session getSession(String handshakeIO) {
//String handshakeIO = sessionIO.getUpgradeRequest().getHeader("Sec-WebSocket-Key");
Session cacheIO = null;
for (Session rowIO : sessionsIO) {
if (handshakeIO.equalsIgnoreCase(rowIO.getUpgradeRequest().getHeader("Sec-WebSocket-Key"))) {
loggerIO.info("FOUND SESSION WITH Sec-WebSocket-Key " + handshakeIO + ".");
cacheIO = rowIO;
}
}
return cacheIO;
}
Fetching Session
#SneakyThrows
#EventHandler
public static void onJoin(UserLoginEvent eventIO) {
Habbo playerIO = eventIO.habbo;
int idIO = playerIO.getHabboInfo().getId();
for (Session rowIO : sessionsIO) {
if (rowIO.isOpen()) {
rowIO.getRemote().sendString(gsonIO.toJson(new ActionPaket("broadcast", "joinedplayer")));
}
}
if (ViceCache.playerIO.containsKey(idIO)) {
Session sessionIO = ViceCache.getSession(ViceCache.playerIO.get(idIO).getSessionIO());
if (sessionIO.isOpen()) {
sessionIO.getRemote().sendString(gsonIO.toJson(new ActionPaket("session", "granted")));
}
playerIO.whisper("Voicechat was successfully connected to Room.");
loggerIO.info("Player " + playerIO.getHabboInfo().getUsername() + " in Cache joined the Server, sending Callback.");
} else {
playerIO.whisper("To use Voice Chat, please download the Offical Vice Client.");
loggerIO.warning("Can't find Player " + playerIO.getHabboInfo().getUsername() + " with ID " + idIO + " in Cache, cannot send Callback for ViceChat.");
}
}
Related
So im trying to implement basic listener for when some value is set on redis, but when i set some value nothing happens and only expiry event gets called.
Subscriber
public class Subscriber {
private static JedisPool pool;
public static void main(String[] args) {
JedisPool pool = new JedisPool("localhost");
Jedis jedis = pool.getResource();
jedis.psubscribe(new SubListener(), "*");
}
}
SubListener
public class SubListener extends JedisPubSub {
#Override
public void onPSubscribe(String pattern, int subscribedChannels) {
System.out.println("onPSubscribe "
+ pattern + " " + subscribedChannels);
}
#Override
public void onPMessage(String pattern, String channel, String message) {
System.out
.println("onPMessage pattern "
+ pattern + " " + channel + " " + message);
}
}
Edit: i found out that i had the notify-keyspace-events in config set to Ex. Now i set it to KEA to call on every event but what should i use to only call the event on set
To only call the event on set, set the config to Ks
My problem is that when i want to respond to an arriveng message i dont get the delivery token back from broker but the message is arrived at the broker. i can see it in the logs. So my question is how to respond with a publish to an incoming message?
This is the way i do and it does not work...
public void setMqttCallback() {
mqttClient.setCallback(new MqttCallback() {
#Override
public void connectionLost(final Throwable throwable) {
System.out.println("Lost connection to Broker because of: " + throwable.getMessage());
}
#Override
public void messageArrived(final String topic, final MqttMessage mqttMessage) throws Exception {
System.out.println("Received on " + topic + ": " + new String(mqttMessage.getPayload()));
topics = new Topics();
//Answer to arriving messages (Logic)
if (topic.equals(topics.getVehicleNavLandmarkInfo(Mqtt.VIN_ID))) {
landmarks = new Landmarks();
MqttMessage message = new MqttMessage(landmarks.getLandmarks().getBytes());
message.setQos(2);
System.out.println("Sending on " + topic + ": " + landmarks.getLandmarks());
mqttClient.publish(topics.getBackendNavLandsmarks(Mqtt.VIN_ID), message);
}
if (topic.equals(topics.getVehicleNavDestination(Mqtt.VIN_ID))) {
routing = new Routing(49.0000, 8.0000, "A");
MqttMessage message = new MqttMessage(routing.getShortestPath().getBytes());
message.setQos(2);
System.out.println("Sending on " + topic + ": " + routing.getShortestPath());
mqttClient.publish(topics.getBackendNavRoute(Mqtt.VIN_ID), message);
}
}
#Override
public void deliveryComplete(final IMqttDeliveryToken iMqttDeliveryToken) {
System.out.println("Delivered Message: " + iMqttDeliveryToken.toString());
}
});
}
The messageArrived method is blocking, so you cannot then try and publish a message using the same mqttClient connection. You need to use another thread that has its own connection to the broker.
If it is a one-off situation then you can start a new thread and do everything in it but if your application will be constantly publishing messages to arriving messages then it would be better to start a thread, connect to broker then wait for information to be passed from the messageArrived method.
I need to invalidate and cleanup active session objects when the JSF application shutdown or tomact shutdown. The following is the code I have written in application scoped bean
#PreDestroy
public void shutdown(){
Map appMap = FacesContext.getCurrentInstance().getExternalContext().getApplicationMap();
Map<String,HttpSession> userSessionMap=(Map<String,HttpSession>)appMap.get("USERS");
log.info("userSessionMap " + userSessionMap);
Set<Entry<String, HttpSession>> entrySet = userSessionMap.entrySet();
for(Entry<String, HttpSession> entry:entrySet){
HttpSession session = entry.getValue();
log.info("HttpSession " + session.getId() + " calling invalidate");
session.invalidate();
}
}
and the following is overwritten HttpSessionListener
#Override
public void sessionDestroyed(HttpSessionEvent se){
HttpSession session = se.getSession();
String id = session.getId();
LoginActionController controller = (LoginActionController) session.getAttribute("userInfo");
log.info("HttpSession " + id + ", LoginActionController " + controller + " is being destroyed...");
if(controller != null){
log.info("User " + controller.getUserName() + " is logged out");
String userName = controller.getUserName();
ServletContext context = session.getServletContext();
Object obj = context.getAttribute("USERS");
if(obj instanceof Map){
Map map = (Map) obj;
map.remove(userName);
RWFacade rWFacade =(RWFacade)session.getAttribute("rWFacade");
rWFacade.closeFacade();
}
}
}
when run this code
session.invalidate();
is not getting executed. I missed anything ? Thanks.
To disable session persitence across restart in tomcat you can uncomment a config in
$TOMCAT_HOME/conf/context.xml
<!-- Uncomment this to disable session persistence across Tomcat restarts
<Manager pathname="" /> -->
May be it will help you.
Hi I created sample jmdns serviceListner, When i run it , It should continue to list services as it finds, But with this my program, It list few services when run and after that it does not list any service. And i have dns-sd in my google chrome browser, So when i browse services in chrome, at that time my program list other services, Otherwise my program doesn't list services. I don't get why ServiceListner itself doesn't detect any subsequent events.
public static void main(String[] args) throws Exception {
String type = "_my-app._tcp.local.";
Enumeration<NetworkInterface> ifc = NetworkInterface.getNetworkInterfaces();
while (ifc.hasMoreElements()) {
NetworkInterface anInterface = ifc.nextElement();
if (anInterface.isUp()) {
Enumeration<InetAddress> addr = anInterface.getInetAddresses();
while (addr.hasMoreElements()) {
InetAddress address = addr.nextElement();
final JmDNS jmdns = JmDNS.create(address, type);
ServiceListenerClass aClass = new ServiceListenerClass();
jmdns.addServiceListener(type, aClass);
}
}
}
}
public static class ServiceListenerClass implements ServiceListener {
public void serviceAdded(ServiceEvent event) {
event.getDNS().requestServiceInfo(event.getType(), event.getName(), true);
}
public void serviceRemoved(ServiceEvent event) {
System.out.println((count--) + " " + event.getInfo().getName());
}
public void serviceResolved(ServiceEvent event) {
System.out.println((count++) + " :Res: " + event.getInfo().getName() + " " + event.getInfo().getPort() + " " + event.getInfo().getApplication()
+ " " + event.getInfo().getDomain() + " " + event.getInfo().getKey());
}
}
I had a similar problem two.
The problem might come from your firewall settings.
In my case the javaw.exe had access to all incoming calls but could not send anything to anyone as the firewall blocked it.
Try turning of the firewall to test you programm and to be shure thats not the firewall causing the problem.
Same issue here. Starting java with the following argument solved it for me:
-Djava.net.preferIPv4Stack=true
I am using spring TransactionSynchronizationManager.Using this manager I register a new Synchronization TransactionSynchronizationAdapter and I override the afterCompletion(int status) method of this TransactionSynchronizationAdapter .
Inside this afterCompletion the value of status must be coming as commited(0) but it is coming as active(0)
Here is the piece of code ::
TransactionSynchronizationManager
.registerSynchronization(new TransactionSynchronizationAdapter() {
public void beforeCompletion(){
int status =Status.STATUS_COMMITTED;
System.out.println("inside before completion block hurray");
}
public void afterCompletion(int status) {
System.out.println("the value of status is " + status);
System.out.println("coming after completion");
if (status == Status.STATUS_COMMITTED) {
final String memcachedKey = getMemcachedKey(pOrderId);
System.out.println("the value of memcached key is inside the aftercompletion " + memcachedKey);
mCmatesMemCachedClient.set(memcachedKey, PROVISIONING_PASS);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Tx commited. Set into memcached:Key="
+ memcachedKey + ",Value=" + PROVISIONING_PASS);
}
}
}
});
}
Don't use Status.STATUS_COMMITTED, it has nothing to do with Spring. Use TransactionSynchronization.STATUS_COMMITTED instead.