當前位置: 首頁>>代碼示例>>Java>>正文


Java Session類代碼示例

本文整理匯總了Java中org.eclipse.jetty.websocket.api.Session的典型用法代碼示例。如果您正苦於以下問題:Java Session類的具體用法?Java Session怎麽用?Java Session使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Session類屬於org.eclipse.jetty.websocket.api包,在下文中一共展示了Session類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: registerSession

import org.eclipse.jetty.websocket.api.Session; //導入依賴的package包/類
/**
 *
 * Stores all websocket client sessions in the internal map 'sessionMap'.
 *
 * Note sessions are 'internally' identified using the encrypted handshake 'Sec-WebSocket-Accept' value and
 * 'externally' identified using an allocated UUID.
 *
 *
 * @param mockExtId
 * @param path
 * @param idleTimeoutMillis
 * @param session
 *
 */
public void registerSession(final String mockExtId, final String path, final long idleTimeoutMillis, final boolean proxyPushIdOnConnect, final Session session) {
    logger.debug("registerSession called");

    session.setIdleTimeout((idleTimeoutMillis > 0) ? idleTimeoutMillis : MAX_IDLE_TIMEOUT_MILLIS );

    final Set<SessionIdWrapper> sessions = sessionMap.getOrDefault(path, new HashSet<SessionIdWrapper>());

    final String assignedId = GeneralUtils.generateUUID();

    sessions.add(new SessionIdWrapper(assignedId, session, GeneralUtils.getCurrentDate()));

    sessionMap.put(path, sessions);

    if (proxyPushIdOnConnect) {
        try {
            sendMessage(assignedId, new WebSocketDTO(path, "clientId: " + assignedId));
        } catch (IOException ex) {
            logger.error("Error pushing client id to client on 1st connect", ex);
        }
    }

}
 
開發者ID:mgtechsoftware,項目名稱:smockin,代碼行數:37,代碼來源:WebSocketServiceImpl.java

示例2: onWebSocketConnect

import org.eclipse.jetty.websocket.api.Session; //導入依賴的package包/類
public void onWebSocketConnect(Session session) {
    this.outbound = session;
    synchronized (connections) {
        connections.add(this);
    }
    Profiling.frontendConnected.countDown();
}
 
開發者ID:LWJGLX,項目名稱:debug,代碼行數:8,代碼來源:Profiling.java

示例3: onWebSocketConnect

import org.eclipse.jetty.websocket.api.Session; //導入依賴的package包/類
@Override
public void onWebSocketConnect(Session sess) {
	super.onWebSocketConnect(sess);
	((WebSocketRemoteEndpoint)sess.getRemote()).setBatchMode(BatchMode.ON);
	handler = new ThreadHandler();
	if (parentServlet.singleThread) {
		BA.firstInstance.postRunnable(handler);
	}
	else {
		Servlet.pool.submit(handler);
	}
}
 
開發者ID:AnywhereSoftware,項目名稱:B4J_Server,代碼行數:13,代碼來源:WebSocketModule.java

示例4: broadcast

import org.eclipse.jetty.websocket.api.Session; //導入依賴的package包/類
/** Broadcast text to all connected clients. */
void broadcast(String message, Session sourceSession) {
	String sourceName = null;
	synchronized(sessionToName) {
		sourceName = sessionToName.get(sourceSession);
	}
	if (sourceName != null && !sourceName.isEmpty()) {
		message = "<strong>" + sourceName + "</strong>: " + message;
	}
	synchronized(sessionToName) {
		for (Session s : sessionToName.keySet()) {
			try {
				if (s.isOpen()) {
					s.getRemote().sendStringByFuture(message);
				}
			} catch (WebSocketException e) {
				System.out.println("The error " + e.getLocalizedMessage() + " occurred. This " 
						+ "can happen if the player dies before a broadcast arrives.");
			}
		}
	}
}
 
開發者ID:nashkevin,項目名稱:Shape-Shmup,代碼行數:23,代碼來源:GameSocket.java

示例5: extractLoadBalanceKey

import org.eclipse.jetty.websocket.api.Session; //導入依賴的package包/類
private void extractLoadBalanceKey(Session session) {
    String setCookieValue =
            session.getUpgradeResponse().getHeader(SDKConstants.CUPID_INTERACTION_HEADER_SET_COOKIE);
    if (setCookieValue != null) {
        setCookieValue = setCookieValue.trim();
        String[] kv = setCookieValue.split(";");
        for (String kvStr : kv) {
            if (kvStr.contains("=")) {
                String[] kAndV = kvStr.split("=");
                if (kAndV.length == 2 && kAndV[0] != null && kAndV[1] != null) {
                    if (SDKConstants.CUPID_INTERACTION_COOKIE_HASH_KEY.equals(kAndV[0].trim())) {
                        loadBalanceHashKey = kAndV[1].trim();
                        LOG.info(subProtocol + " - loadbalance key:" + loadBalanceHashKey);
                        return;
                    }
                }
            }
        }
    }
}
 
開發者ID:aliyun,項目名稱:aliyun-cupid-sdk,代碼行數:21,代碼來源:WebSocketClient.java

示例6: onConnect

import org.eclipse.jetty.websocket.api.Session; //導入依賴的package包/類
@OnWebSocketConnect
public void onConnect(Session session) {
    LOG.info(webSocketClient.getSubProtocol() + " - Got connect.");
    if (mode == SDKConstants.INTERACTION_CLIENT_INPUT_MODE_INPUTSTREAM) {
        if (inputBuf == null) {
            this.inputBuf = ByteBuffer.allocate(SDKConstants.WEBSOCKET_MAX_BINARY_MESSAGE_SIZE);
            this.inputBuf.limit(0);
            this.inputStream = new ByteBufferBackedInputStream(inputBuf);
        }
    }
    if (outputBuf == null) {
        this.outputBuf = ByteBuffer.allocate(SDKConstants.WEBSOCKET_MAX_BINARY_MESSAGE_SIZE);
        this.outputStream = new ByteBufferBackedOutputStream(outputBuf, session);
    } else {
        synchronized (outputBuf) {
            ((ByteBufferBackedOutputStream) this.outputStream).setSession(session);
            outputBuf.notify();
        }
    }
    this.closed = false;
}
 
開發者ID:aliyun,項目名稱:aliyun-cupid-sdk,代碼行數:22,代碼來源:InteractionSocket.java

示例7: onWebSocketConnect

import org.eclipse.jetty.websocket.api.Session; //導入依賴的package包/類
@Override
public void onWebSocketConnect(final Session session) {
	MAP.put(this.flag = this.getConnectFlag(session), session);
	MsgTo to = new MsgTo(MsgType.connect, "", this.flag, "200",
			System.currentTimeMillis(), null);
	send(session, JsonUtil.toJsonStr(to));

	// $version < 1.2.2 ;
	// s.scheduleWithFixedDelay(new Runnable() {
	// {
	//
	// Jwslistner.send(session, "200");
	// }
	//
	// @Override
	// public void run() {
	// Jwslistner.send(session, "heartbeat");
	// }
	// }, 30, 30, TimeUnit.SECONDS);

	this.getWh().onConnect(session, flag);
}
 
開發者ID:Sunature,項目名稱:websocket,代碼行數:23,代碼來源:Jwslistner.java

示例8: send

import org.eclipse.jetty.websocket.api.Session; //導入依賴的package包/類
public static boolean send(Session session, String msg) {
	if (session == null)
		return false;
	try {
		if (session.isOpen())
			session.getRemote().sendString(msg);
	} catch (IOException e) {
		e.printStackTrace();
		return false;
	}
	return true;
}
 
開發者ID:Sunature,項目名稱:websocket,代碼行數:13,代碼來源:Jwslistner.java

示例9: WorkWebsocket

import org.eclipse.jetty.websocket.api.Session; //導入依賴的package包/類
public WorkWebsocket(Backend backend) {
    backend.getWorkObservable(workResponses).subscribe((req) -> {
        String msg = GSON.toJson(req);
        int offset = 0;
        for (Session session : sessions) {
            final int finalOffset = ++offset;
            Schedulers.io().scheduleDirect(()-> {
                try {
                    JsonObject finalMsg = GSON.fromJson(msg, JsonObject.class);
                    finalMsg.addProperty("offset", finalOffset);
                    session.getRemote().sendString(GSON.toJson(finalMsg));
                    System.out.println("Send message to a session");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    });

}
 
開發者ID:toonsevrin,項目名稱:IOTAFaucet,代碼行數:21,代碼來源:Frontend.java

示例10: testDepthStreamWatcher

import org.eclipse.jetty.websocket.api.Session; //導入依賴的package包/類
@Test
public void testDepthStreamWatcher() throws Exception, BinanceApiException {
    Session session = binanceApi.websocketDepth(symbol, new BinanceWebSocketAdapterDepth() {
        @Override
        public void onMessage(BinanceEventDepthUpdate message) {
            log.info(message.toString());
        }
    });
    Thread.sleep(3000);
    session.close();
}
 
開發者ID:webcerebrium,項目名稱:java-binance-api,代碼行數:12,代碼來源:DepthStreamTest.java

示例11: testTradesStreamWatcher

import org.eclipse.jetty.websocket.api.Session; //導入依賴的package包/類
@Test
public void testTradesStreamWatcher() throws Exception, BinanceApiException {
    Session session = binanceApi.websocketTrades(symbol, new BinanceWebSocketAdapterAggTrades() {
        @Override
        public void onMessage(BinanceEventAggTrade message) {
            log.info(message.toString());
        }
    });
    Thread.sleep(5000);
    session.close();
}
 
開發者ID:webcerebrium,項目名稱:java-binance-api,代碼行數:12,代碼來源:AggTradesStreamTest.java

示例12: testKlinesStreamWatcher

import org.eclipse.jetty.websocket.api.Session; //導入依賴的package包/類
@Test
public void testKlinesStreamWatcher() throws Exception, BinanceApiException {
    Session session = binanceApi.websocketKlines(symbol, BinanceInterval.ONE_MIN, new BinanceWebSocketAdapterKline() {
        @Override
        public void onMessage(BinanceEventKline message) {
            log.info(message.toString());
        }
    });
    Thread.sleep(3000);
    session.close();
}
 
開發者ID:webcerebrium,項目名稱:java-binance-api,代碼行數:12,代碼來源:KlinesStreamTest.java

示例13: killRequestedJob

import org.eclipse.jetty.websocket.api.Session; //導入依賴的package包/類
private void killRequestedJob(ExecutionStatus executionStatus, Session session) {

		if (Constants.KILL.equalsIgnoreCase(executionStatus.getType())) {

			logger.info("Kill request received for job - " + executionStatus.getJobId());

			final String jobId = executionStatus.getJobId().trim();

			for (Session openSession : allSessions.keySet()) {

				if (openSession.isOpen()) {
					try {

						if (allSessions.get(openSession).get(Constants.CLIENTID) != null) {

							if (((String) allSessions.get(openSession).get(Constants.CLIENTID))
									.equalsIgnoreCase(Constants.ENGINE_CLIENT + executionStatus.getJobId())) {

								logger.debug("Before sending kill" + jobId);
								openSession.getRemote().sendStringByFuture("");
								logger.debug("After sending kill" + jobId);
							}
						}
					} catch (Exception e) {
						logger.error("Failed to send kill request for - " + jobId, e);
					}
				}
			}
		}

	}
 
開發者ID:capitalone,項目名稱:Hydrograph,代碼行數:32,代碼來源:ExecutionTrackingWebsocketHandler.java

示例14: onConnect

import org.eclipse.jetty.websocket.api.Session; //導入依賴的package包/類
/**
 * Callback hook for Connection open events.
 *
 * @param session the user session which is opened.
 */
@OnWebSocketConnect
public void onConnect(Session session) {
	this.session = session;
	this.futureSession = null; // don't need this anymore
	this.addr = session.getRemoteAddress().getAddress();
	this.remotePort = session.getRemoteAddress().getPort();
	this.localAddr = session.getLocalAddress().getAddress();
	this.localPort = session.getLocalAddress().getPort();
	this.path = session.getUpgradeRequest().getRequestURI().getPath();
	if (session.getUpgradeRequest() instanceof ClientUpgradeRequest) {
		this.key = ((ClientUpgradeRequest)session.getUpgradeRequest()).getKey();
	}
	else {
		this.key = session.getUpgradeRequest().getHeader("Sec-WebSocket-Key");
	}
    if (log.isLoggable(Level.INFO)) 
    	log.log(Level.INFO,"Connected with "+((addr==null)?"<null>":addr.toString())+" through local address "+localAddr.getHostAddress());
    pool.addSession(this);
    pool.getInclusionCallback().onStartConnection(this);
}
 
開發者ID:gustavohbf,項目名稱:robotoy,代碼行數:26,代碼來源:WebSocketHandlerImpl.java

示例15: initializeNativeSession

import org.eclipse.jetty.websocket.api.Session; //導入依賴的package包/類
@Override
public void initializeNativeSession(Session session) {
	super.initializeNativeSession(session);

	this.id = ObjectUtils.getIdentityHexString(getNativeSession());
	this.uri = session.getUpgradeRequest().getRequestURI();

	this.headers = new HttpHeaders();
	this.headers.putAll(getNativeSession().getUpgradeRequest().getHeaders());
	this.headers = HttpHeaders.readOnlyHttpHeaders(headers);

	this.acceptedProtocol = session.getUpgradeResponse().getAcceptedSubProtocol();

	List<ExtensionConfig> source = getNativeSession().getUpgradeResponse().getExtensions();
	this.extensions = new ArrayList<WebSocketExtension>(source.size());
	for (ExtensionConfig ec : source) {
		this.extensions.add(new WebSocketExtension(ec.getName(), ec.getParameters()));
	}

	if (this.user == null) {
		this.user = session.getUpgradeRequest().getUserPrincipal();
	}
}
 
開發者ID:langtianya,項目名稱:spring4-understanding,代碼行數:24,代碼來源:JettyWebSocketSession.java


注:本文中的org.eclipse.jetty.websocket.api.Session類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。