当前位置: 首页>>代码示例>>Java>>正文


Java WebSocketSession类代码示例

本文整理汇总了Java中org.springframework.web.socket.WebSocketSession的典型用法代码示例。如果您正苦于以下问题:Java WebSocketSession类的具体用法?Java WebSocketSession怎么用?Java WebSocketSession使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


WebSocketSession类属于org.springframework.web.socket包,在下文中一共展示了WebSocketSession类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: PlayMediaPipeline

import org.springframework.web.socket.WebSocketSession; //导入依赖的package包/类
public PlayMediaPipeline(KurentoClient kurento, String user, final WebSocketSession session) {
  // Media pipeline
  pipeline = kurento.createMediaPipeline();

  // Media Elements (WebRtcEndpoint, PlayerEndpoint)
  webRtc = new WebRtcEndpoint.Builder(pipeline).build();
  player = new PlayerEndpoint.Builder(pipeline, RECORDING_PATH + user + RECORDING_EXT).build();

  // Connection
  player.connect(webRtc);

  // Player listeners
  player.addErrorListener(new EventListener<ErrorEvent>() {
    @Override
    public void onEvent(ErrorEvent event) {
      log.info("ErrorEvent: {}", event.getDescription());
      sendPlayEnd(session);
    }
  });
}
 
开发者ID:jake-kent,项目名称:TLIVideoConferencingv2,代码行数:21,代码来源:PlayMediaPipeline.java

示例2: apply

import org.springframework.web.socket.WebSocketSession; //导入依赖的package包/类
@Override
public void apply(ApiRequest request, ApiResponse response, WebSocketSession session) {
    String msg = StringEscapeUtils.escapeHtml4(request.getMsg());
    if (StringUtils.isBlank(msg)) {
        return;
    }
    Map<String, Object> attributes = session.getAttributes();
    String id = session.getId();
    DrawPlayerInfo info = ((DrawPlayerInfo) attributes.get("info"));
    DrawGuessContext ctx = (DrawGuessContext) attributes.get("ctx");
    DrawGameStatus status = ctx.status();
    ArrayList<String> msgs = new ArrayList<>(2);
    if (status == DrawGameStatus.RUN) {
        if (StringUtils.equals(id, ctx.getCurrentUser())) {
            protectSecret(info, ctx, msg, msgs);
        } else {
            processGussPerson(info, ctx, msg, msgs);
        }
    } else {
        msgs.add("<b>" + info.getName() + "</b>: " + msg);
    }
    response.setCode(DrawCode.DRAW_MSG.getCode()).setData(msgs);
}
 
开发者ID:csdbianhua,项目名称:telemarket-skittle-alley,代码行数:24,代码来源:UserMsgHandler.java

示例3: sendPlayEnd

import org.springframework.web.socket.WebSocketSession; //导入依赖的package包/类
public void sendPlayEnd(WebSocketSession session) {
  try {
    JsonObject response = new JsonObject();
    response.addProperty("id", "playEnd");
    session.sendMessage(new TextMessage(response.toString()));
  } catch (IOException e) {
    log.error("Error sending playEndOfStream message", e);
  }

  // Release pipeline
  pipeline.release();
  this.webRtc = null;
}
 
开发者ID:jake-kent,项目名称:TLIVideoConferencingv2,代码行数:14,代码来源:PlayMediaPipeline.java

示例4: stop

import org.springframework.web.socket.WebSocketSession; //导入依赖的package包/类
private synchronized void stop(WebSocketSession session) throws IOException {
  String sessionId = session.getId();
  if (teacherUserSession != null && teacherUserSession.getSession().getId().equals(sessionId)) {
    for (UserSession student : students.values()) {
      JsonObject response = new JsonObject();
      response.addProperty("id", "stopCommunication");
      student.sendMessage(response);
    }

    log.info("Releasing media pipeline");
    if (pipeline != null) {
      pipeline.release();
    }
    pipeline = null;
    teacherUserSession = null;
  } else if (students.containsKey(sessionId)) {
    if (students.get(sessionId).getWebRtcEndpoint() != null) {
      students.get(sessionId).getWebRtcEndpoint().release();
    }
    students.remove(sessionId);
  }
}
 
开发者ID:jake-kent,项目名称:TLIVideoConferencingv2,代码行数:23,代码来源:CallHandler.java

示例5: gatherStatistics

import org.springframework.web.socket.WebSocketSession; //导入依赖的package包/类
public void gatherStatistics(WebSocketSession session, long conversationId) throws IOException {
	Call call = callManager.getCall(conversationId);
	Map<String, Map<String, Stats>> statistics = new HashMap<>();
	call.getParticipants().stream().forEach(participant -> {
				statistics.put(
						participant.getUserName(),
						participant.getUserCall().getOutgoingMediaEndpoint() != null ? participant.getUserCall().getOutgoingMediaEndpoint().getStats() : null
				);
				Map<Long, WebRtcEndpoint> e = participant.getUserCall().getIncomingMediaEndpoints();
				e.forEach((p, val) ->
					statistics.put(participant.getUserName() + " - " + p,
							val.getStats())
				);
			}
		);

	sender.sendAnonymous(session, "stats.gather", statistics);
}
 
开发者ID:zralock,项目名称:CTUConference,代码行数:19,代码来源:StatsCommServiceImpl.java

示例6: authorizeGroupAccess

import org.springframework.web.socket.WebSocketSession; //导入依赖的package包/类
/**
 * Authorizes user access to the group. Group must be active and user must have privileges.
 * @param groupId
 * @param session
 * @param privilege
 * @return
 * @throws WSMessageException
 */
protected boolean authorizeGroupAccess(long groupId, WebSocketSession session, MemberPrivilege privilege) throws WSMessageException {
	UserSession userSession = registry.getBySession(session);
	if(userSession != null) {
		long userId = userSession.getUserId();
		if(!groupService.isActive(groupId)) throw new WSMessageException(WSMessageException.NOT_AUTHORIZED);
		switch(privilege) {
			case ADMINISTRATION:
				return groupService.hasAdminPermissions(userId, groupId);
			case CALL_PERFORMING:
				return groupService.isMember(userId, groupId)
					&& (groupService.hasLectorPermissions(userId, groupId)
						|| groupService.getMembershipRole(userId, groupId) == MembershipRole.TEAM_MEMBER);
			case CALL_LISTENING:
				return groupService.isMember(userId, groupId);
			case BASIC:
				return groupService.isMember(userId, groupId);
		}
	}
	throw new WSMessageException(WSMessageException.NOT_AUTHORIZED);
}
 
开发者ID:zralock,项目名称:CTUConference,代码行数:29,代码来源:AppMessageReceiver.java

示例7: connectToProxiedTarget

import org.springframework.web.socket.WebSocketSession; //导入依赖的package包/类
private void connectToProxiedTarget(WebSocketSession session) {
	URI sessionUri = session.getUri();
	ZuulWebSocketProperties.WsBrokerage wsBrokerage = getWebSocketBrokarage(
			sessionUri);

	Assert.notNull(wsBrokerage, "wsBrokerage");

	String path = getWebSocketServerPath(wsBrokerage, sessionUri);
	Assert.notNull(path, "Web socket uri path");

	String routeHost = zuulPropertiesResolver.getRouteHost(wsBrokerage);
	Assert.notNull(routeHost, "routeHost");

       String uri = ServletUriComponentsBuilder
               .fromHttpUrl(routeHost)
               .path(path)
               .replaceQuery(sessionUri.getQuery())
               .toUriString();

	ProxyWebSocketConnectionManager connectionManager = new ProxyWebSocketConnectionManager(
			messagingTemplate, stompClient, session, headersCallback, uri);
	connectionManager.errorHandler(this.errorHandler);
	managers.put(session, connectionManager);
	connectionManager.start();
}
 
开发者ID:mthizo247,项目名称:spring-cloud-netflix-zuul-websocket,代码行数:26,代码来源:ProxyWebSocketHandler.java

示例8: authorizeUserSocket

import org.springframework.web.socket.WebSocketSession; //导入依赖的package包/类
/**
   * Authorizes web
* socket via the token, that was provided to the client during
* the authentication process.
   * @param params should contain "user" param with user id
   * @param session
   * @throws IOException
   */
  private void authorizeUserSocket(JsonObject params, WebSocketSession session) throws IOException, WSMessageException {
      final String token = parser.getStringParameter(params, "token");
boolean authorized = false;
AppUser appUser = authTokenCache.getAuthUserByToken(UUID.fromString(token));
if(appUser != null) {
	UserSession oldSession;
	if((oldSession = userRegistry.getByUserId(appUser.getId())) != null) {
		deactivateUserSocket(oldSession);
	}
	UserSession userSession = new UserSession(appUser.getId(), appUser.getFullName(), session, messageSender);
	userRegistry.register(userSession);
	notifierService.notifyUserStateChanged(appUser.getId(), ContactState.ONLINE);
	authorized = true;
}
UserDTO userDTO = new UserDTO(appUser.getId(), appUser.getEmail(), appUser.getFirstName(), appUser.getLastName(), token.toString());
AuthenticationDTO authDTO = new AuthenticationDTO(authorized, userDTO);
messageSender.sendAnonymous(session, "authentication.authorize-socket", authDTO);
  }
 
开发者ID:zralock,项目名称:CTUConference,代码行数:27,代码来源:AuthenticationMessageReceiver.java

示例9: close

import org.springframework.web.socket.WebSocketSession; //导入依赖的package包/类
public void close(WebSocketSession webSocketSession) {
    Replicator replicator = replicatorMap.remove(webSocketSession.getId());
    if (replicator != null) {
        try {
            replicator.close();
            webSocketSession.close();
        } catch (IOException e) {
            logger.warn(e.getMessage());
        }
    }
    RxClient rxClient = rxClientMap.get(webSocketSession.getId());
    if (rxClient != null) {
        rxClient.shutdown();
    }
    observableMap.remove(webSocketSession.getId());
    authMap.remove(webSocketSession.getId());
}
 
开发者ID:wu191287278,项目名称:sc-generator,代码行数:18,代码来源:RedisTextWebSocketHandler.java

示例10: testSessionIdAnnotation

import org.springframework.web.socket.WebSocketSession; //导入依赖的package包/类
@Test
public void testSessionIdAnnotation() throws Exception {
	CompletableFutureWebSocketHandler result = new CompletableFutureWebSocketHandler();

	try (WebSocketSession wsSession = startWebSocketSession(result,
			DataFormat.SMILE)) {
		List<WampRole> roles = new ArrayList<>();
		roles.add(new WampRole("caller"));
		HelloMessage helloMessage = new HelloMessage("realm", roles);
		sendMessage(DataFormat.SMILE, wsSession, helloMessage);

		WelcomeMessage welcomeMessage = result.getWelcomeMessage();

		CallMessage callMessage = new CallMessage(22L, "sessionIdAnnotation");
		sendMessage(DataFormat.SMILE, wsSession, callMessage);

		WampMessage wampResult = result.getWampMessage();

		assertThat(wampResult).isInstanceOf(ResultMessage.class);
		ResultMessage resultMessage = (ResultMessage) wampResult;
		assertThat(resultMessage.getRequestId()).isEqualTo(22L);
		assertThat(resultMessage.getArgumentsKw()).isNull();
		assertThat(resultMessage.getArguments())
				.containsExactly("session id: " + welcomeMessage.getSessionId());
	}
}
 
开发者ID:ralscha,项目名称:wamp2spring,代码行数:27,代码来源:CallParameterTest.java

示例11: handleTextMessage

import org.springframework.web.socket.WebSocketSession; //导入依赖的package包/类
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message)
		throws Exception {

	try {
		WampMessage wampMessage = WampMessage.deserialize(this.jsonFactory,
				message.asBytes());

		if (wampMessage instanceof WelcomeMessage) {
			this.welcomeMessageFuture.complete((WelcomeMessage) wampMessage);
		}
		else {
			this.receivedMessages.add(wampMessage);
			if (this.receivedMessages.size() == this.noOfResults) {
				this.messageFuture.complete(this.receivedMessages);
			}

		}

	}
	catch (IOException e) {
		this.welcomeMessageFuture.completeExceptionally(e);
		this.messageFuture.completeExceptionally(e);
	}
}
 
开发者ID:ralscha,项目名称:wamp2spring,代码行数:26,代码来源:CompletableFutureWebSocketHandler.java

示例12: sendWampMessage

import org.springframework.web.socket.WebSocketSession; //导入依赖的package包/类
protected WampMessage sendWampMessage(WampMessage msg, DataFormat dataFormat)
		throws InterruptedException, ExecutionException, TimeoutException,
		IOException {
	CompletableFutureWebSocketHandler result = new CompletableFutureWebSocketHandler();
	WebSocketClient webSocketClient = new StandardWebSocketClient();

	try (WebSocketSession webSocketSession = webSocketClient
			.doHandshake(result, getHeaders(dataFormat), wampEndpointUrl()).get()) {

		List<WampRole> roles = new ArrayList<>();
		roles.add(new WampRole("publisher"));
		roles.add(new WampRole("subscriber"));
		roles.add(new WampRole("caller"));
		HelloMessage helloMessage = new HelloMessage("realm", roles);
		sendMessage(dataFormat, webSocketSession, helloMessage);

		result.getWelcomeMessage();

		sendMessage(dataFormat, webSocketSession, msg);

		return result.getWampMessage();
	}
}
 
开发者ID:ralscha,项目名称:wamp2spring,代码行数:24,代码来源:BaseWampTest.java

示例13: apply

import org.springframework.web.socket.WebSocketSession; //导入依赖的package包/类
@Override
public void apply(ApiRequest request, ApiResponse response, WebSocketSession session) {
    DrawGuessContext ctx = (DrawGuessContext) session.getAttributes().get("ctx");
    JSONObject obj = JSONObject.parseObject(request.getMsg());
    boolean ready = obj.getBooleanValue(STATUS_NAME);
    String id = obj.getString(ID_NAME);
    DrawPlayerInfo info = ((DrawPlayerInfo) session.getAttributes().get("info"));
    if (ctx.status() != DrawGameStatus.READY) {
        return;
    }
    if (ready && info.status() == DrawUserStatus.WAIT) {
        info.setStatus(DrawUserStatus.READY);
        ctx.addPlayer(info);
    } else if (!ready && info.status() == DrawUserStatus.READY) {
        info.setStatus(DrawUserStatus.WAIT);
        ctx.removePlayer(id);
    }
    response.setCode(DrawCode.USER_READY.getCode()).setData(info);
}
 
开发者ID:csdbianhua,项目名称:telemarket-skittle-alley,代码行数:20,代码来源:ReadyHandler.java

示例14: afterConnectionEstablished

import org.springframework.web.socket.WebSocketSession; //导入依赖的package包/类
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
  ss = new SocketSession(session);

  TextMessage message = new TextMessage("Socket session opened!");
  session.sendMessage(message);
  logger.info("Opened new session in instance " + this);
  //boop();
}
 
开发者ID:sinaa,项目名称:train-simulator,代码行数:10,代码来源:WebSocketHandler.java

示例15: toRef

import org.springframework.web.socket.WebSocketSession; //导入依赖的package包/类
private PluginWebsocketSessionRef toRef(WebSocketSession session) throws IOException {
    URI sessionUri = session.getUri();
    String path = sessionUri.getPath();
    path = path.substring(WebSocketConfiguration.WS_PLUGIN_PREFIX.length());
    if (path.length() == 0) {
        throw new IllegalArgumentException("URL should contain plugin token!");
    }
    String[] pathElements = path.split("/");
    String pluginToken = pathElements[0];
    // TODO: cache
    PluginMetaData pluginMd = pluginService.findPluginByApiToken(pluginToken);
    if (pluginMd == null) {
        throw new InvalidParameterException("Can't find plugin with specified token!");
    } else {
        SecurityUser currentUser = (SecurityUser) session.getAttributes().get(WebSocketConfiguration.WS_SECURITY_USER_ATTRIBUTE);
        TenantId tenantId = currentUser.getTenantId();
        CustomerId customerId = currentUser.getCustomerId();
        if (PluginApiController.validatePluginAccess(pluginMd, tenantId, customerId)) {
            PluginApiCallSecurityContext securityCtx = new PluginApiCallSecurityContext(pluginMd.getTenantId(), pluginMd.getId(), tenantId,
                    currentUser.getCustomerId());
            return new BasicPluginWebsocketSessionRef(UUID.randomUUID().toString(), securityCtx, session.getUri(), session.getAttributes(),
                    session.getLocalAddress(), session.getRemoteAddress());
        } else {
            throw new SecurityException("Current user is not allowed to use this plugin!");
        }
    }
}
 
开发者ID:osswangxining,项目名称:iotplatform,代码行数:28,代码来源:PluginWebSocketHandler.java


注:本文中的org.springframework.web.socket.WebSocketSession类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。