本文整理汇总了Java中javax.websocket.Session类的典型用法代码示例。如果您正苦于以下问题:Java Session类的具体用法?Java Session怎么用?Java Session使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Session类属于javax.websocket包,在下文中一共展示了Session类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testClientDropsConnection
import javax.websocket.Session; //导入依赖的package包/类
@Test
public void testClientDropsConnection() throws Exception {
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
ctx.addApplicationListener(Bug58624Config.class.getName());
Tomcat.addServlet(ctx, "default", new DefaultServlet());
ctx.addServletMapping("/", "default");
WebSocketContainer wsContainer =
ContainerProvider.getWebSocketContainer();
tomcat.start();
SimpleClient client = new SimpleClient();
URI uri = new URI("ws://localhost:" + getPort() + Bug58624Config.PATH);
Session session = wsContainer.connectToServer(client, uri);
// Break point A required on following line
session.close();
}
示例2: msgReceived
import javax.websocket.Session; //导入依赖的package包/类
@OnMessage
public void msgReceived(ChatMessage msg, Session s) {
msg.from(user);
if (msg.getMsg().equals(LOGOUT_MSG)) {
try {
s.close();
return;
} catch (IOException ex) {
Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
ChatEventBus.getInstance().publishChat(msg);
System.out.println("Chat Message placed on HZ Topic " + CHAT_TOPIC_NAME);
}
示例3: onClose
import javax.websocket.Session; //导入依赖的package包/类
@Override
public void onClose(Session session, CloseReason closeReason) {
Room room = getRoom(false);
if (room != null) {
room.invokeAndWait(new Runnable() {
@Override
public void run() {
try {
// Player can be null if it couldn't enter the room
if (player != null) {
// Remove this player from the room.
player.removeFromRoom();
// Set player to null to prevent NPEs when onMessage events
// are processed (from other threads) after onClose has been
// called from different thread which closed the Websocket session.
player = null;
}
} catch (RuntimeException ex) {
log.error("Unexpected exception: " + ex.toString(), ex);
}
}
});
}
}
示例4: updateJobTrackingStatus
import javax.websocket.Session; //导入依赖的package包/类
/**
*
* Called by web socket server, message contain execution tracking status that updated on job canvas.
*
* @param message the message
* @param session the session
*/
@OnMessage
public void updateJobTrackingStatus(String message, Session session) {
final String status = message;
Display.getDefault().asyncExec(new Runnable() {
public void run() {
Gson gson = new Gson();
ExecutionStatus executionStatus=gson.fromJson(status, ExecutionStatus.class);
IWorkbenchPage page = PlatformUI.getWorkbench().getWorkbenchWindows()[0].getActivePage();
IEditorReference[] refs = page.getEditorReferences();
for (IEditorReference ref : refs){
IEditorPart editor = ref.getEditor(false);
if(editor instanceof ELTGraphicalEditor){
ELTGraphicalEditor editPart=(ELTGraphicalEditor)editor;
if(editPart.getJobId().equals(executionStatus.getJobId()) || (((editPart.getContainer()!=null) &&
(editPart.getContainer().getUniqueJobId().equals(executionStatus.getJobId()))) && editPart.getContainer().isOpenedForTracking() )){
TrackingStatusUpdateUtils.INSTANCE.updateEditorWithCompStatus(executionStatus, (ELTGraphicalEditor)editor,false);
}
}
}
}
});
}
示例5: onOpen
import javax.websocket.Session; //导入依赖的package包/类
/**
* 连接建立成功调用的方法-与前端JS代码对应
*
* @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
@OnOpen
public void onOpen(Session session, EndpointConfig config) {
// 单个会话对象保存
this.session = session;
webSocketSet.add(this); // 加入set中
this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
String uId = (String) httpSession.getAttribute("userid"); // 获取当前用户
String sessionId = httpSession.getId();
this.userid = uId + "|" + sessionId;
if (!OnlineUserlist.contains(this.userid)) {
OnlineUserlist.add(userid); // 将用户名加入在线列表
}
routetabMap.put(userid, session); // 将用户名和session绑定到路由表
System.out.println(userid + " -> 已上线");
String message = getMessage(userid + " -> 已上线", "notice", OnlineUserlist);
broadcast(message); // 广播
}
示例6: unregisterUser
import javax.websocket.Session; //导入依赖的package包/类
@OnClose
public void unregisterUser(Session websocket, CloseReason reason) throws JSONException, IOException {
String login = websocket.getUserPrincipal().getName();
if (login == null) {
return;
}
Integer organisationId = Integer
.valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_ORGANISATION_ID).get(0));
KumaliveDTO kumalive = kumalives.get(organisationId);
if (kumalive == null) {
return;
}
KumaliveUser user = kumalive.learners.remove(login);
if (user != null) {
Integer userId = user.userDTO.getUserID();
if (kumalive.raisedHand != null) {
kumalive.raisedHand.remove(userId);
}
if (userId.equals(kumalive.speaker)) {
kumalive.speaker = null;
}
}
sendRefresh(kumalive);
}
示例7: onOpen
import javax.websocket.Session; //导入依赖的package包/类
/**连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session,EndpointConfig config){
HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
if(StorageUtil.init(httpSession).getLoginMemberId()!=ReturnUtil.NOT_LOGIN_CODE){
long userId = StorageUtil.init(httpSession).getLoginMemberId();
mapUS.put(userId,session);
mapSU.put(session,userId);
//上线通知由客户端自主发起
onlineCount++; //在线数加1
System.out.println("用户"+userId+"进入WebSocket!当前在线人数为" + onlineCount);
getUserKey(userId);
}else{
try {
session.close();
System.out.println("未获取到用户信息,关闭WebSocket!");
} catch (IOException e) {
System.out.println("关闭WebSocket失败!");
}
}
}
示例8: echoBinaryMessage
import javax.websocket.Session; //导入依赖的package包/类
@OnMessage
public void echoBinaryMessage(Session session, ByteBuffer msg,
boolean last) {
try {
session.getBasicRemote().sendBinary(msg, last);
} catch (IOException e) {
try {
session.close();
} catch (IOException e1) {
// Ignore
}
}
}
示例9: unregisterUser
import javax.websocket.Session; //导入依赖的package包/类
/**
* Removes Learner websocket from the collection.
*/
@OnClose
public void unregisterUser(Session session, CloseReason reason) {
String login = session.getUserPrincipal().getName();
if (login == null) {
return;
}
Long lessonId = Long.valueOf(session.getRequestParameterMap().get(AttributeNames.PARAM_LESSON_ID).get(0));
Map<String, Session> lessonWebsockets = CommandWebsocketServer.websockets.get(lessonId);
if (lessonWebsockets == null) {
return;
}
lessonWebsockets.remove(login);
}
示例10: downHandPrompt
import javax.websocket.Session; //导入依赖的package包/类
/**
* Tell learners that the teacher finished a question
*/
private void downHandPrompt(JSONObject requestJSON, Session websocket) throws IOException, JSONException {
Integer organisationId = Integer
.valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_ORGANISATION_ID).get(0));
KumaliveDTO kumalive = kumalives.get(organisationId);
User user = getUser(websocket);
Integer userId = user.getUserId();
if (!KumaliveWebsocketServer.getSecurityService().hasOrgRole(organisationId, userId,
new String[] { Role.GROUP_MANAGER, Role.MONITOR }, "kumalive down hand prompt", false)) {
String warning = "User " + userId + " is not a monitor of organisation " + organisationId;
logger.warn(warning);
return;
}
kumalive.raiseHandPrompt = false;
kumalive.raisedHand.clear();
if (logger.isDebugEnabled()) {
logger.debug("Teacher " + userId + " finished a question in Kumalive " + kumalive.id);
}
sendRefresh(kumalive);
}
示例11: broadcast
import javax.websocket.Session; //导入依赖的package包/类
public void broadcast(@Observes @LeaderDataQualifier String leaderboard) {
for (final Session s : CLIENTS) {
if (s != null && s.isOpen()) {
/**
* Asynchronous push
*/
s.getAsyncRemote().sendText(leaderboard, new SendHandler() {
@Override
public void onResult(SendResult result) {
if (result.isOK()) {
//Logger.getLogger(MeetupGroupsLiveLeaderboardEndpoint.class.getName()).log(Level.INFO, " sent to client {0}", s.getId());
} else {
Logger.getLogger(MeetupGroupsLiveLeaderboardEndpoint.class.getName()).log(Level.SEVERE, "Could not send to client " + s.getId(),
result.getException());
}
}
});
}
}
}
示例12: handleMessage
import javax.websocket.Session; //导入依赖的package包/类
@OnMessage
public void handleMessage(Session session, String message) throws IOException {
logger.info("Received msg: " + message);
String sendMsg = "Reversed: " + new StringBuilder(message).reverse();
session.getBasicRemote().sendText(sendMsg);
logger.info("Send msg: " + sendMsg);
}
示例13: closeWebSocketConnection
import javax.websocket.Session; //导入依赖的package包/类
/**
*
* Close websocket client connection.
* @param session
*/
public void closeWebSocketConnection(Session session){
try {
Thread.sleep(DELAY);
} catch (InterruptedException e1) {
}
if (session != null && session.isOpen()) {
try {
CloseReason closeReason = new CloseReason(CloseCodes.NORMAL_CLOSURE,"Closed");
session.close(closeReason);
logger.info("Session closed");
} catch (IOException e) {
logger.error("Fail to close connection ",e);
}
}
}
示例14: onError
import javax.websocket.Session; //导入依赖的package包/类
@Override
public final void onError(Session session, Throwable throwable) {
if (methodMapping.getOnError() == null) {
log.error(sm.getString("pojoEndpointBase.onError",
pojo.getClass().getName()), throwable);
} else {
try {
methodMapping.getOnError().invoke(
pojo,
methodMapping.getOnErrorArgs(pathParameters, session,
throwable));
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.error(sm.getString("pojoEndpointBase.onErrorFail",
pojo.getClass().getName()), t);
}
}
}
示例15: unregisterUser
import javax.websocket.Session; //导入依赖的package包/类
/**
* When user leaves the activity.
*/
@OnClose
public void unregisterUser(Session websocket, CloseReason reason) {
Long toolContentID = Long
.valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_TOOL_CONTENT_ID).get(0));
websockets.get(toolContentID).remove(websocket);
if (log.isDebugEnabled()) {
// If there was something wrong with the connection, put it into logs.
log.debug("User " + websocket.getUserPrincipal().getName() + " left Dokumaran with Tool Content ID: "
+ toolContentID
+ (!(reason.getCloseCode().equals(CloseCodes.GOING_AWAY)
|| reason.getCloseCode().equals(CloseCodes.NORMAL_CLOSURE))
? ". Abnormal close. Code: " + reason.getCloseCode() + ". Reason: "
+ reason.getReasonPhrase()
: ""));
}
}