本文整理汇总了Java中javax.websocket.OnOpen类的典型用法代码示例。如果您正苦于以下问题:Java OnOpen类的具体用法?Java OnOpen怎么用?Java OnOpen使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
OnOpen类属于javax.websocket包,在下文中一共展示了OnOpen类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: onOpen
import javax.websocket.OnOpen; //导入依赖的package包/类
@OnOpen
public void onOpen(Session session, @PathParam("uuid") String uuid) {
UUID key = UUID.fromString(uuid);
peers.put(key, session);
JsonArrayBuilder builder = Json.createArrayBuilder();
for (StatusEventType statusEventType : StatusEventType.values()) {
JsonObjectBuilder object = Json.createObjectBuilder();
builder.add(object.add(statusEventType.name(), statusEventType.getMessage()).build());
}
RemoteEndpoint.Async asyncRemote = session.getAsyncRemote();
asyncRemote.sendText(builder.build().toString());
// Send pending messages
List<String> messages = messageBuffer.remove(key);
if (messages != null) {
messages.forEach(asyncRemote::sendText);
}
}
示例2: onOpen
import javax.websocket.OnOpen; //导入依赖的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); // 广播
}
示例3: onOpen
import javax.websocket.OnOpen; //导入依赖的package包/类
@OnOpen
public void onOpen(Session session) throws NamingException {
logger.info("Open session:" + session.getId());
ManagedExecutorService mes = doLookup("java:comp/DefaultManagedExecutorService");
final Session s = session;
mes.execute(new Runnable() {
@Override
public void run() {
try {
for (int i = 0; i < 3; i++) {
sleep(10000);
s.getBasicRemote().sendText("Message from server");
}
} catch (InterruptedException | IOException e) {
logger.log(SEVERE, "connection error", e);
}
}
});
}
开发者ID:PacktPublishing,项目名称:Mastering-Java-EE-Development-with-WildFly,代码行数:20,代码来源:WebSocketServer.java
示例4: registerUser
import javax.websocket.OnOpen; //导入依赖的package包/类
/**
* Registeres the Learner for processing.
*/
@OnOpen
public void registerUser(Session websocket) throws JSONException, IOException {
Long toolContentID = Long
.valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_TOOL_CONTENT_ID).get(0));
Set<Session> toolContentWebsockets = websockets.get(toolContentID);
if (toolContentWebsockets == null) {
toolContentWebsockets = ConcurrentHashMap.newKeySet();
websockets.put(toolContentID, toolContentWebsockets);
}
toolContentWebsockets.add(websocket);
if (log.isDebugEnabled()) {
log.debug("User " + websocket.getUserPrincipal().getName() + " entered Dokumaran with toolContentId: "
+ toolContentID);
}
}
示例5: registerUser
import javax.websocket.OnOpen; //导入依赖的package包/类
/**
* Registeres the Learner for processing.
*/
@OnOpen
public void registerUser(Session websocket) throws JSONException, IOException {
Long toolSessionId = Long
.valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_TOOL_SESSION_ID).get(0));
Set<Session> sessionWebsockets = websockets.get(toolSessionId);
if (sessionWebsockets == null) {
sessionWebsockets = ConcurrentHashMap.newKeySet();
websockets.put(toolSessionId, sessionWebsockets);
}
sessionWebsockets.add(websocket);
if (log.isDebugEnabled()) {
log.debug("User " + websocket.getUserPrincipal().getName()
+ " entered Leader Selection with toolSessionId: " + toolSessionId);
}
}
示例6: registerUser
import javax.websocket.OnOpen; //导入依赖的package包/类
/**
* Registeres the Learner for processing by SendWorker.
*/
@OnOpen
public void registerUser(Session session) throws IOException {
Long lessonId = Long.valueOf(session.getRequestParameterMap().get(AttributeNames.PARAM_LESSON_ID).get(0));
Set<Websocket> sessionWebsockets = PresenceWebsocketServer.websockets.get(lessonId);
if (sessionWebsockets == null) {
sessionWebsockets = ConcurrentHashMap.newKeySet();
PresenceWebsocketServer.websockets.put(lessonId, sessionWebsockets);
}
Websocket websocket = new Websocket(session);
sessionWebsockets.add(websocket);
Roster roster = PresenceWebsocketServer.rosters.get(lessonId);
if (roster == null) {
boolean imEnabled = Boolean.valueOf(session.getRequestParameterMap().get("imEnabled").get(0));
// build a new roster object
roster = new Roster(lessonId, imEnabled);
PresenceWebsocketServer.rosters.put(lessonId, roster);
}
new Thread(() -> {
try {
// websocket communication bypasses standard HTTP filters, so Hibernate session needs to be initialised manually
HibernateSessionManager.openSession();
SendWorker.send(lessonId, websocket.nickName);
} finally {
HibernateSessionManager.closeSession();
}
}).start();
if (PresenceWebsocketServer.log.isDebugEnabled()) {
PresenceWebsocketServer.log
.debug("User " + websocket.nickName + " entered Presence Chat with lesson ID: " + lessonId);
}
}
示例7: registerUser
import javax.websocket.OnOpen; //导入依赖的package包/类
/**
* Registeres the Learner for processing by SendWorker.
*/
@OnOpen
public void registerUser(Session session) throws IOException {
Long toolSessionId = Long
.valueOf(session.getRequestParameterMap().get(AttributeNames.PARAM_TOOL_SESSION_ID).get(0));
Set<Websocket> sessionWebsockets = LearningWebsocketServer.websockets.get(toolSessionId);
if (sessionWebsockets == null) {
sessionWebsockets = ConcurrentHashMap.newKeySet();
LearningWebsocketServer.websockets.put(toolSessionId, sessionWebsockets);
}
final Set<Websocket> finalSessionWebsockets = sessionWebsockets;
String userName = session.getUserPrincipal().getName();
new Thread(() -> {
try {
// websocket communication bypasses standard HTTP filters, so Hibernate session needs to be initialised manually
HibernateSessionManager.openSession();
ChatUser chatUser = LearningWebsocketServer.getChatService().getUserByLoginNameAndSessionId(userName,
toolSessionId);
Websocket websocket = new Websocket(session, chatUser.getNickname(), chatUser.getUserId(), getPortraitId(chatUser.getUserId()));
finalSessionWebsockets.add(websocket);
// update the chat window immediatelly
SendWorker.send(toolSessionId);
if (LearningWebsocketServer.log.isDebugEnabled()) {
LearningWebsocketServer.log
.debug("User " + userName + " entered Chat with toolSessionId: " + toolSessionId);
}
} finally {
HibernateSessionManager.closeSession();
}
}).start();
}
示例8: registerUser
import javax.websocket.OnOpen; //导入依赖的package包/类
/**
* Registeres the Learner for processing by SendWorker.
*/
@OnOpen
public void registerUser(Session websocket) throws JSONException, IOException {
Long toolSessionId = Long
.valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_TOOL_SESSION_ID).get(0));
Set<Session> sessionWebsockets = LearningWebsocketServer.websockets.get(toolSessionId);
if (sessionWebsockets == null) {
sessionWebsockets = ConcurrentHashMap.newKeySet();
LearningWebsocketServer.websockets.put(toolSessionId, sessionWebsockets);
Map<Long, Map<Long, Boolean>> sessionCache = new TreeMap<>();
LearningWebsocketServer.cache.put(toolSessionId, sessionCache);
}
sessionWebsockets.add(websocket);
if (LearningWebsocketServer.log.isDebugEnabled()) {
LearningWebsocketServer.log.debug("User " + websocket.getUserPrincipal().getName()
+ " entered Scratchie with toolSessionId: " + toolSessionId);
}
}
示例9: registerUser
import javax.websocket.OnOpen; //导入依赖的package包/类
/**
* Registeres the Learner for processing by SendWorker.
*/
@OnOpen
public void registerUser(Session websocket) throws JSONException, IOException {
Long toolSessionId = Long
.valueOf(websocket.getRequestParameterMap().get(AttributeNames.PARAM_TOOL_SESSION_ID).get(0));
Set<Session> sessionWebsockets = LearningWebsocketServer.websockets.get(toolSessionId);
if (sessionWebsockets == null) {
sessionWebsockets = ConcurrentHashMap.newKeySet();
LearningWebsocketServer.websockets.put(toolSessionId, sessionWebsockets);
}
sessionWebsockets.add(websocket);
if (LearningWebsocketServer.log.isDebugEnabled()) {
LearningWebsocketServer.log.debug("User " + websocket.getUserPrincipal().getName()
+ " entered Scribe with toolSessionId: " + toolSessionId);
}
new Thread(() -> {
try {
HibernateSessionManager.openSession();
SendWorker.send(toolSessionId, websocket);
} catch (Exception e) {
log.error("Error while sending messages", e);
} finally {
HibernateSessionManager.closeSession();
}
}).start();
}
示例10: userConnectedCallback
import javax.websocket.OnOpen; //导入依赖的package包/类
@OnOpen
public void userConnectedCallback(@PathParam("user") String user, Session s) {
if (USERS.contains(user)) {
try {
dupUserDetected = true;
s.getBasicRemote().sendText("Username " + user + " has been taken. Retry with a different name");
s.close();
return;
} catch (IOException ex) {
Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
this.s = s;
s.getUserProperties().put("user", user);
this.user = user;
USERS.add(user);
welcomeNewJoinee();
announceNewJoinee();
}
示例11: userConnectedCallback
import javax.websocket.OnOpen; //导入依赖的package包/类
@OnOpen
public void userConnectedCallback(@PathParam("user") String user, Session s) {
if (USERS.contains(user)) {
try {
dupUserDetected = true;
s.getBasicRemote().sendObject(new DuplicateUserNotification(user));
s.close();
return;
} catch (Exception ex) {
Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
this.s = s;
SESSIONS.add(s);
s.getUserProperties().put("user", user);
this.user = user;
USERS.add(user);
welcomeNewJoinee();
announceNewJoinee();
}
示例12: onOpen
import javax.websocket.OnOpen; //导入依赖的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失败!");
}
}
}
示例13: openSocket
import javax.websocket.OnOpen; //导入依赖的package包/类
/**
* Open a socket connection to a client from the web server
*
* @param session The session that just opened
*/
@OnOpen
public void openSocket(@PathParam(RT_COMPUTE_ENDPOINT_PARAM) ConnectionType type,
Session session) {
session.setMaxIdleTimeout(0);
String sessionId = session.getId();
if (type == ConnectionType.SUBSCRIBER) {
LOG.info("Got a new subscriber connection request with ID {}. Saving session", sessionId);
// cleanup sessions
Set<Session> closedSessions = Sets.newHashSet();
for (Session existingSession : sessions) {
if (!existingSession.isOpen()) {
closedSessions.add(existingSession);
}
}
sessions.removeAll(closedSessions);
sessions.add(session);
LOG.info("Active sessions {}. Collecting {} sessions",
sessions.size(), closedSessions.size());
} else {
LOG.info("Got a new publisher connection request with ID {}", sessionId);
}
}
示例14: onOpen
import javax.websocket.OnOpen; //导入依赖的package包/类
@OnOpen
public void onOpen(Session session,@PathParam("username") String username) {
try{
client.add(session);
user.put(URLEncoder.encode(username, "UTF-8"),URLEncoder.encode(username, "UTF-8"));
JSONObject jo = new JSONObject();
JSONArray ja = new JSONArray();
//获得在线用户列表
Set<String> key = user.keySet();
for (String u : key) {
ja.add(u);
}
jo.put("onlineUser", ja);
session.getBasicRemote().sendText(jo.toString());
}catch(Exception e){
//do nothing
}
}
示例15: onOpen
import javax.websocket.OnOpen; //导入依赖的package包/类
@OnOpen
public void onOpen(Session session, @PathParam("uuid") String uuid) {
UUID key = UUID.fromString(uuid);
peers.put(key, session);
JsonArrayBuilder builder = Json.createArrayBuilder();
for (StatusMessage statusMessage : StatusMessage.values()) {
JsonObjectBuilder object = Json.createObjectBuilder();
builder.add(object.add(statusMessage.name(), statusMessage.getMessage()).build());
}
RemoteEndpoint.Async asyncRemote = session.getAsyncRemote();
asyncRemote.sendText(builder.build().toString());
// Send pending messages
List<String> messages = messageBuffer.remove(key);
if (messages != null) {
messages.forEach(asyncRemote::sendText);
}
}