本文整理匯總了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);
}
}