本文整理匯總了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);
}
});
}
示例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);
}
示例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;
}
示例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);
}
}
示例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);
}
示例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);
}
示例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();
}
示例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);
}
示例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());
}
示例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());
}
}
示例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);
}
}
示例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();
}
}
示例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);
}
示例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();
}
示例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!");
}
}
}