Java Code Examples for org.springframework.web.socket.WebSocketSession#sendMessage()

The following examples show how to use org.springframework.web.socket.WebSocketSession#sendMessage() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BaseProxyHandler.java    From Jpom with MIT License 6 votes vote down vote up
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    Map<String, Object> attributes = session.getAttributes();
    NodeModel nodeModel = (NodeModel) attributes.get("nodeInfo");
    UserModel userInfo = (UserModel) attributes.get("userInfo");
    String dataValue = (String) attributes.get(dataParName);
    String userName = UserModel.getOptUserName(userInfo);
    userName = URLUtil.encode(userName);
    if (nodeModel != null) {
        String url = NodeForward.getSocketUrl(nodeModel, nodeUrl);
        url = StrUtil.format(url, dataValue, userName);
        // 连接节点
        ProxySession proxySession = new ProxySession(url, session);
        session.getAttributes().put("proxySession", proxySession);
    }
    session.sendMessage(new TextMessage(StrUtil.format("欢迎加入:{} 会话id:{} ", userInfo.getName(), session.getId())));
}
 
Example 2
Source File: WebSocketHandlerTest.java    From data-highway with Apache License 2.0 5 votes vote down vote up
@Override
public void afterConnectionEstablished(WebSocketSession session) throws java.io.IOException {
  ObjectMapper mapper = new ObjectMapper();
  String event = mapper.writeValueAsString(TestMessage.getTestMessage());
  int half = event.length() / 2;
  String part1 = event.substring(0, half);
  String part2 = event.substring(half);
  session.sendMessage(new BinaryMessage(part1.getBytes(UTF_8), false));
  session.sendMessage(new BinaryMessage(part2.getBytes(UTF_8), true));
}
 
Example 3
Source File: SocketSessionUtil.java    From Jpom with MIT License 5 votes vote down vote up
public static void send(WebSocketSession session, String msg) throws IOException {
    if (StrUtil.isEmpty(msg)) {
        return;
    }
    if (!session.isOpen()) {
        throw new RuntimeException("session close ");
    }
    try {
        LOCK.lock(session.getId());
        IOException exception = null;
        int tryCount = 0;
        do {
            tryCount++;
            if (exception != null) {
                // 上一次有异常、休眠 500
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ignored) {
                }
            }
            try {
                session.sendMessage(new TextMessage(msg));
                exception = null;
                break;
            } catch (IOException e) {
                DefaultSystemLog.getLog().error("发送消息失败:" + tryCount, e);
                exception = e;
            }
        } while (tryCount <= ERROR_TRY_COUNT);
        if (exception != null) {
            throw exception;
        }
    } finally {
        LOCK.unlock(session.getId());
    }
}
 
Example 4
Source File: InfoHandler.java    From openvidu with Apache License 2.0 5 votes vote down vote up
public void sendInfo(String info){
	for (WebSocketSession session : this.sessions.values()) {
		try {
			this.semaphore.acquire();
			session.sendMessage(new TextMessage(info));
			this.semaphore.release();
		} catch (IOException | InterruptedException e) {
			e.printStackTrace();
		}
	}
}
 
Example 5
Source File: ServiceDiscovery.java    From artemis with Apache License 2.0 5 votes vote down vote up
protected void subscribe(final WebSocketSession session, final DiscoveryConfig discoveryConfig) {
    try {
        if (discoveryConfig == null) {
            return;
        }
        if (session == null) {
            return;
        }
        final TextMessage message = new TextMessage(JacksonJsonSerializer.INSTANCE.serialize(discoveryConfig));
        session.sendMessage(message);
    } catch (final Throwable e) {
        logger.warn("subscribe service failed", e);
    }
}
 
Example 6
Source File: MsfHandler.java    From TrackRay with GNU General Public License v3.0 5 votes vote down vote up
@Override
    public  void afterConnectionEstablished(WebSocketSession session)
            throws Exception {

        if (Constant.AVAILABLE_METASPLOIT && metasploit.login()){
            flag = true;
            int console = metasploit.createConsole();
            String banner = metasploit.banner();
            session.sendMessage(Message.RED(banner));
        }else{
            session.sendMessage(Message.RED("[-]msf远程接口配置有误\n"));
            /*outputStream = new WebsocketOutputStream(new ByteArrayOutputStream() , session);
            CommandLine commandLine = CommandLine.parse("E:\\Hack\\PenTools\\metasploit\\metasploit-framework\\bin\\msfconsole.bat");
            defaultExecutor = new DefaultExecutor();
            ExecuteWatchdog watchdog = new ExecuteWatchdog(Integer.MAX_VALUE);
            DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
            PluginDataOutputStream websocketSendMessageOutputStream = new PluginDataOutputStream();
            BufferedInputStream bufferedInputStream = new BufferedInputStream(new PipedInputStream(websocketSendMessageOutputStream));
            PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream,outputStream,bufferedInputStream);
            inputWriter = new PrintWriter(websocketSendMessageOutputStream);
            inputWriter.println();
            inputWriter.flush();

            defaultExecutor.setStreamHandler(pumpStreamHandler);
            defaultExecutor.setWatchdog(watchdog);
            defaultExecutor.execute(commandLine,resultHandler);
*/
        }
        sessions.put(session.getId(),null);
        super.afterConnectionEstablished(session);
    }
 
Example 7
Source File: StompSubProtocolHandler.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Invoked when no
 * {@link #setErrorHandler(StompSubProtocolErrorHandler) errorHandler}
 * is configured to send an ERROR frame to the client.
 * @deprecated as of Spring 4.2, in favor of
 * {@link #setErrorHandler(StompSubProtocolErrorHandler) configuring}
 * a {@code StompSubProtocolErrorHandler}
 */
@Deprecated
protected void sendErrorMessage(WebSocketSession session, Throwable error) {
	StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.ERROR);
	headerAccessor.setMessage(error.getMessage());

	byte[] bytes = this.stompEncoder.encode(headerAccessor.getMessageHeaders(), EMPTY_PAYLOAD);
	try {
		session.sendMessage(new TextMessage(bytes));
	}
	catch (Throwable ex) {
		// Could be part of normal workflow (e.g. browser tab closed)
		logger.debug("Failed to send STOMP ERROR to client", ex);
	}
}
 
Example 8
Source File: GemWebSocketMessage.java    From gem with MIT License 5 votes vote down vote up
/**
 * 接受消息
 */
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
	System.out.println("接受消息执行的方法" +message.getPayload());
	// 接收到客户端消息时调用
	super.handleTextMessage(session, message);
	session.sendMessage(new TextMessage(String.valueOf(System.currentTimeMillis())));
}
 
Example 9
Source File: SocketHandler.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws InterruptedException, IOException {

    for (WebSocketSession webSocketSession : sessions) {
        if (webSocketSession.isOpen() && !session.getId().equals(webSocketSession.getId())) {
            webSocketSession.sendMessage(message);
        }
    }
}
 
Example 10
Source File: AbstractSockJsIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test(timeout = 5000)
public void fallbackAfterConnectTimeout() throws Exception {
	TestClientHandler clientHandler = new TestClientHandler();
	this.testFilter.sleepDelayMap.put("/xhr_streaming", 10000L);
	this.testFilter.sendErrorMap.put("/xhr_streaming", 503);
	initSockJsClient(createXhrTransport());
	this.sockJsClient.setConnectTimeoutScheduler(this.wac.getBean(ThreadPoolTaskScheduler.class));
	WebSocketSession clientSession = sockJsClient.doHandshake(clientHandler, this.baseUrl + "/echo").get();
	assertEquals("Fallback didn't occur", XhrClientSockJsSession.class, clientSession.getClass());
	TextMessage message = new TextMessage("message1");
	clientSession.sendMessage(message);
	clientHandler.awaitMessage(message, 5000);
	clientSession.close();
}
 
Example 11
Source File: CustomWebSocketHandler.java    From spring-websocket-template with MIT License 5 votes vote down vote up
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) {
    try {
        TextMessage ackMessage = new TextMessage("ACK: " + message.getPayload());
        session.sendMessage(ackMessage);
    } catch (IOException e) {
        logger.warn("Failed to send message to session {}, ignoring quietly", session.getId());
    }
}
 
Example 12
Source File: AbstractSockJsIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test(timeout = 5000)
public void fallbackAfterConnectTimeout() throws Exception {
	TestClientHandler clientHandler = new TestClientHandler();
	this.testFilter.sleepDelayMap.put("/xhr_streaming", 10000L);
	this.testFilter.sendErrorMap.put("/xhr_streaming", 503);
	initSockJsClient(createXhrTransport());
	this.sockJsClient.setConnectTimeoutScheduler(this.wac.getBean(ThreadPoolTaskScheduler.class));
	WebSocketSession clientSession = sockJsClient.doHandshake(clientHandler, this.baseUrl + "/echo").get();
	assertEquals("Fallback didn't occur", XhrClientSockJsSession.class, clientSession.getClass());
	TextMessage message = new TextMessage("message1");
	clientSession.sendMessage(message);
	clientHandler.awaitMessage(message, 5000);
	clientSession.close();
}
 
Example 13
Source File: AbstractSockJsIntegrationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void fallbackAfterTransportFailure() throws Exception {
	this.testFilter.sendErrorMap.put("/websocket", 200);
	this.testFilter.sendErrorMap.put("/xhr_streaming", 500);
	TestClientHandler handler = new TestClientHandler();
	initSockJsClient(createWebSocketTransport(), createXhrTransport());
	WebSocketSession session = this.sockJsClient.doHandshake(handler, this.baseUrl + "/echo").get();
	assertEquals("Fallback didn't occur", XhrClientSockJsSession.class, session.getClass());
	TextMessage message = new TextMessage("message1");
	session.sendMessage(message);
	handler.awaitMessage(message, 5000);
}
 
Example 14
Source File: StompSubProtocolHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Invoked when no
 * {@link #setErrorHandler(StompSubProtocolErrorHandler) errorHandler}
 * is configured to send an ERROR frame to the client.
 */
private void sendErrorMessage(WebSocketSession session, Throwable error) {
	StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.ERROR);
	headerAccessor.setMessage(error.getMessage());

	byte[] bytes = this.stompEncoder.encode(headerAccessor.getMessageHeaders(), EMPTY_PAYLOAD);
	try {
		session.sendMessage(new TextMessage(bytes));
	}
	catch (Throwable ex) {
		// Could be part of normal workflow (e.g. browser tab closed)
		logger.debug("Failed to send STOMP ERROR to client", ex);
	}
}
 
Example 15
Source File: PluginServiceImpl.java    From TrackRay with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 使用插件处理方法(websocket)
 * @param session websocket会话对象
 * @param key 插件KEY
 * @return
 * @throws IOException
 */
@Override
public boolean usePlugin(WebSocketSession session, String key) throws IOException {
    if (!getContext().containsBean(key)){
        session.sendMessage(Message.NORMAL("插件不存在"));
        return false;
    }
    AbstractPlugin bean = null;
    try {
        bean = (AbstractPlugin) getBean(key);
    } catch (Exception e) {
        session.sendMessage(Message.NORMAL("插件不合法"));
        return false;
    }
    if (bean!=null && bean instanceof AbstractPlugin){
    }else {
        session.sendMessage(Message.NORMAL("插件不合法"));
        return false;
    }

    Rule rule = bean.currentRule();
    if (!rule.enable()){
        session.sendMessage(Message.NORMAL("插件未启用"));
        return false;
    }
    if (!rule.websocket()) {
        session.sendMessage(Message.NORMAL("该插件不支持websocket"));
        return false;
    }

    JSONObject ruleObj = rule(key);
    String tableStr = this.pluginToTable(ruleObj);
    session.sendMessage(Message.NORMAL(tableStr));
    return true;
}
 
Example 16
Source File: EventsHandler.java    From khs-trouble-maker with Apache License 2.0 4 votes vote down vote up
private void sendEvents(WebSocketSession session) throws JsonProcessingException, IOException {
	session.sendMessage(new TextMessage(objectMapper.writeValueAsString(this.eventContainer)));
}
 
Example 17
Source File: MyHandler.java    From code with Apache License 2.0 4 votes vote down vote up
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    Integer uid = (Integer) session.getAttributes().get("uid");
    session.sendMessage(new TextMessage(uid + ", 你好!欢迎连接到ws服务"));
}
 
Example 18
Source File: AbstractSockJsIntegrationTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
	session.sendMessage(message);
}
 
Example 19
Source File: AllServicesChangeWsHandler.java    From artemis with Apache License 2.0 4 votes vote down vote up
@Override
public boolean publish(final InstanceChange instanceChange) {
    try {
        if ((instanceChange == null) || (instanceChange.getInstance() == null)) {
            return true;
        }

        final String serviceId = instanceChange.getInstance().getServiceId();
        if (StringValues.isNullOrWhitespace(serviceId)) {
            return true;
        }

        final String instanceId = instanceChange.getInstance().getInstanceId();
        final String changeType = instanceChange.getChangeType();

        if (MapValues.isNullOrEmpty(sessions)) {
            return true;
        }
        final TextMessage message = new TextMessage(JacksonJsonSerializer.INSTANCE.serialize(instanceChange));
        List<WebSocketSession> allSessions = Lists.newArrayList(sessions.values());
        for (final WebSocketSession session : allSessions) {
            if (session.isOpen()) {
                try {
                    synchronized(session){
                        session.sendMessage(message);
                        MetricLoggerHelper.logPublishEvent("success", serviceId, instanceId, changeType);
                    }
                } catch (final Exception sendException) {
                    MetricLoggerHelper.logPublishEvent("failed", serviceId, instanceId, changeType);
                    logger.error("websocket session send message failed", sendException);
                    try{
                        session.close();
                    } catch (final Exception closeException) {
                        logger.warn("close websocket session failed", closeException);
                    }
                }
            }
        }
        logger.info(String.format("send instance change message to %d sessions: %s", sessions.size(), instanceChange));
        return true;
    } catch (final Exception e) {
        logger.error("send instance change failed", e);
        return false;
    }
}
 
Example 20
Source File: MarcoHandler.java    From Project with Apache License 2.0 4 votes vote down vote up
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
	logger.info("Received message: " + message.getPayload());
	Thread.sleep(2000);
	session.sendMessage(new TextMessage("Polo!"));
}