public void send(final WebSocketMessage message, final boolean clearSessionId) { // return session status to client message.setSessionValid(isAuthenticated()); // whether to clear the token (all command except LOGIN (for now) should absolutely do this!) if (clearSessionId) { message.setSessionId(null); } // set callback message.setCallback(callback); if (isAuthenticated() || "STATUS".equals(message.getCommand())) { String msg = gson.toJson(message, WebSocketMessage.class); logger.log( Level.FINE, "############################################################ SENDING \n{0}", msg); try { session.getRemote().sendString(msg); } catch (Throwable t) { logger.log(Level.WARNING, "Unable to send websocket message to remote client"); } } else { logger.log(Level.WARNING, "NOT sending message to unauthenticated client."); } }
/* Socket message envoyé */ public void sendMessage(String str) { try { session.getRemote().sendString(str); } catch (IOException e) { e.printStackTrace(); } }
@Override public void onWebSocketConnect(Session sess) { connected = true; final String spath = getFirstValue(sess, "path"); final String sset = getFirstValue(sess, "dataset"); final boolean writing = Boolean.parseBoolean(getFirstValue(sess, "writingExpected")); final Path path = Paths.get(spath); try { WatchService myWatcher = path.getFileSystem().newWatchService(); QueueReader fileWatcher = new QueueReader(myWatcher, sess, spath, sset, writing); // We may only monitor a directory if (Files.isDirectory(path)) { path.register(myWatcher, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE); } else { path.getParent().register(myWatcher, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE); } Thread th = new Thread(fileWatcher, path.getFileName() + " Watcher"); th.setDaemon(true); th.setPriority(Thread.MAX_PRIORITY - 2); th.start(); if (diagInfo != null) diagInfo.record("Start Thread", th.getName()); } catch (Exception ne) { logger.error("Cannot watch " + path, ne); try { sess.getRemote().sendString(ne.getMessage()); } catch (IOException e) { logger.warn("Cannot write to remote " + sess, e); } } }
@OnWebSocketMessage public void onText(Session session, String message) { if (session.isOpen()) { System.out.printf("Echoing back message [%s]%n", message); // echo the message back session.getRemote().sendString(message, null); } }
/** * Sends a response packet from the server to the client. * * <p>Synchronized so that only one thread can send a client a message at a time. * * @param packet the response packet */ public synchronized void sendResponse(Packet packet) { try { session.getRemote().sendString(packet.getJson().toString()); } catch (IOException ioe) { System.out.println( "Sending response failed, session id = " + session.getRemoteAddress().toString()); } }
@Override public void onWebSocketText(String message) { LOG.debug("onWebSocketText({})", message); calls.incrementAndGet(); if (message.equalsIgnoreCase("openSessions")) { Collection<WebSocketSession> sessions = container.getOpenSessions(); StringBuilder ret = new StringBuilder(); ret.append("openSessions.size=").append(sessions.size()).append('\n'); int idx = 0; for (WebSocketSession sess : sessions) { ret.append('[').append(idx++).append("] ").append(sess.toString()).append('\n'); } session.getRemote().sendStringByFuture(ret.toString()); session.close(StatusCode.NORMAL, "ContainerSocket"); } else if (message.equalsIgnoreCase("calls")) { session.getRemote().sendStringByFuture(String.format("calls=%,d", calls.get())); } }
@Test public void testBatchModeAuto() throws Exception { URI uri = URI.create("ws://localhost:" + connector.getLocalPort()); final CountDownLatch latch = new CountDownLatch(1); WebSocketAdapter adapter = new WebSocketAdapter() { @Override public void onWebSocketText(String message) { latch.countDown(); } }; try (Session session = client.connect(adapter, uri).get()) { RemoteEndpoint remote = session.getRemote(); Future<Void> future = remote.sendStringByFuture("batch_mode_on"); // The write is aggregated and therefore completes immediately. future.get(1, TimeUnit.MICROSECONDS); // Wait for the echo. Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); } }
public synchronized void keepAlive() throws Exception { checkConnected(); connection.getRemote().sendString("\n"); }
public synchronized void sendFrame(StompFrame frame) throws Exception { checkConnected(); connection.getRemote().sendString(frame.format()); }
public synchronized void sendRawFrame(String rawFrame) throws Exception { checkConnected(); connection.getRemote().sendString(rawFrame); }
/** * In order to implement a file watcher, we loop forever ensuring requesting to take the next * item from the file watchers queue. */ @Override public void run() { final Path path = Paths.get(spath); try { // We wait until the file we are told to monitor exists. while (!Files.exists(path)) { Thread.sleep(200); } // get the first event before looping WatchKey key = null; while (session.isOpen() && connected && (key = watcher.take()) != null) { try { if (!Files.exists(path)) continue; for (WatchEvent<?> event : key.pollEvents()) { if (!Files.exists(path)) continue; Path epath = (Path) event.context(); if (!Files.isDirectory(path) && !path.endsWith(epath)) continue; try { // Data has changed, read its shape and publish the event using a web socket. final IDataHolder holder = ServiceHolder.getLoaderService().getData(spath, new IMonitor.Stub()); if (holder == null) continue; // We do not stop if the loader got nothing. final ILazyDataset lz = sdataset != null && !"".equals(sdataset) ? holder.getLazyDataset(sdataset) : holder.getLazyDataset(0); if (lz == null) continue; // We do not stop if the loader got nothing. if (lz instanceof IDynamicDataset) { ((IDynamicDataset) lz).refreshShape(); } if (writing) { ServiceHolder.getLoaderService().clearSoftReferenceCache(spath); } final DataEvent evt = new DataEvent(lz.getName(), lz.getShape()); evt.setFilePath(spath); // We manually JSON the object because we // do not want a dependency and object simple String json = evt.encode(); session.getRemote().sendString(json); if (diagInfo != null) diagInfo.record("JSON Send", json); } catch (HDF5FunctionArgumentException h5error) { // This happens sometimes when the file is not ready to read. logger.trace("Path might not be ready to read " + path); continue; } catch (Exception ne) { logger.error("Exception getting data from " + path); continue; } break; } } finally { key.reset(); } } } catch (Exception e) { logger.error("Exception monitoring " + path, e); if (session.isOpen()) session.close(403, e.getMessage()); } finally { if (diagInfo != null) diagInfo.record("Close Thread", Thread.currentThread().getName()); try { watcher.close(); } catch (IOException e) { logger.error("Error closing watcher", e); } } }