当前位置: 首页>>代码示例>>Java>>正文


Java WebSocketContainer.connectToServer方法代码示例

本文整理汇总了Java中javax.websocket.WebSocketContainer.connectToServer方法的典型用法代码示例。如果您正苦于以下问题:Java WebSocketContainer.connectToServer方法的具体用法?Java WebSocketContainer.connectToServer怎么用?Java WebSocketContainer.connectToServer使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在javax.websocket.WebSocketContainer的用法示例。


在下文中一共展示了WebSocketContainer.connectToServer方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: testClientDropsConnection

import javax.websocket.WebSocketContainer; //导入方法依赖的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();
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:22,代码来源:TestWsRemoteEndpointImplServer.java

示例2: connect

import javax.websocket.WebSocketContainer; //导入方法依赖的package包/类
private void connect() throws Exception {
	while (sessionServer != null && !sessionServer.isOpen()) {
		break;
	}
	SSLContext context = createSSLContext();
	SecureSocketClient endpoint = new SecureSocketClient();

	Configurator configurator = new Configurator() {

		@Override
		public void beforeRequest(Map<String, List<String>> headers) {
			headers.put(SEC_WEB_SOCKET_PROTOCOL_STRING, singletonList("configured-proto"));
		}

	};
	ClientEndpointConfig clientEndpointConfig = create().configurator(configurator)
			.preferredSubprotocols(asList(new String[] { "foo", "bar", "configured-proto" })).build();
	clientEndpointConfig.getUserProperties().put(SSL_CONTEXT, context);

	final WebSocketContainer serverContainer = getWebSocketContainer();
	URI uri = new URI("wss://127.0.0.1:8443/secure-test/session");
	serverContainer.connectToServer(endpoint, clientEndpointConfig, uri);
	awake();
}
 
开发者ID:PacktPublishing,项目名称:Mastering-Java-EE-Development-with-WildFly,代码行数:25,代码来源:SessionSecureTestCase.java

示例3: webSocketsStatusTest

import javax.websocket.WebSocketContainer; //导入方法依赖的package包/类
/**
 * Ensures that CDI event is relayed over the webSocket status endpoint.
 *
 * @throws Exception when the test has failed
 */
@Test
public void webSocketsStatusTest() throws Exception {
    //given
    UUID uuid = UUID.randomUUID();
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    URI uri = UriBuilder.fromUri(deploymentUrl).scheme("ws").path("status").path(uuid.toString()).build();
    container.connectToServer(endpoint, uri);

    //when
    Thread.sleep(200);
    testEvent.fire(new StatusMessageEvent(uuid, StatusEventType.GITHUB_CREATE,
                                          singletonMap(EXTRA_DATA_KEY, "http://github.com/dummy-project-location")));
    endpoint.getLatch().await(1, TimeUnit.SECONDS);

    //then
    assertNotNull("a status message should have been send", endpoint.getMessage());
    assertTrue(endpoint.getMessage().contains(EXTRA_DATA_KEY));
}
 
开发者ID:fabric8-launcher,项目名称:launcher-backend,代码行数:24,代码来源:MissionControlStatusEndpointIT.java

示例4: testServerFirstCall

import javax.websocket.WebSocketContainer; //导入方法依赖的package包/类
@Test
public void testServerFirstCall() throws Exception {
	logger.info("start websocket server first call test");
	reset();

	final WebSocketContainer serverContainer = getWebSocketContainer();
	serverContainer.connectToServer(WebSocketClient.class, url.toURI().resolve("chat"));

	assertEquals("the message is sent at the start of client", "Server received [Hello]", getMessage());
	sleep(30000);
	assertEquals("It comes from the server. First", "Message from server", getMessage());
	assertEquals("It comes from the server. Second", "Message from server", getMessage());
	assertEquals("It comes from the server. Third", "Message from server", getMessage());
	assertNull("no other messages", getMessage());

	assertTrue("PostConstruct method on client endpoint instance not called.", postConstructCalled);
}
 
开发者ID:PacktPublishing,项目名称:Mastering-Java-EE-Development-with-WildFly,代码行数:18,代码来源:IntroTestCase.java

示例5: testConnectToServerEndpointInvalidScheme

import javax.websocket.WebSocketContainer; //导入方法依赖的package包/类
@Test(expected=javax.websocket.DeploymentException.class)
public void testConnectToServerEndpointInvalidScheme() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    wsContainer.connectToServer(TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ftp://" + getHostName() + ":" + getPort() +
                    TesterEchoServer.Config.PATH_ASYNC));
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:17,代码来源:TestWsWebSocketContainer.java

示例6: sendMessage

import javax.websocket.WebSocketContainer; //导入方法依赖的package包/类
/**
 * Sends message to the WebSocket server.
 *
 * @param endpoint The server endpoint
 * @param msg The message
 * @return a return message
 */
private String sendMessage(String endpoint, String msg) {

    LOGGER.config(() -> "Sending message: " + msg);

    String returnValue = "-1";
    try {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        String uri = serviceUrl + endpoint;
        Session session = container.connectToServer(this, URI.create(uri));
        session.getBasicRemote().sendText(msg != null ? msg : "");
        returnValue = session.getId();
        
        session.close();

    } catch (DeploymentException | IOException ex) {
        LOGGER.warning(ex.getMessage());
    }

    return returnValue;
}
 
开发者ID:ivargrimstad,项目名称:snoopee,代码行数:28,代码来源:SnoopEERegistrationClient.java

示例7: connectToServer

import javax.websocket.WebSocketContainer; //导入方法依赖的package包/类
/**
 * Connects the current agent to a server.
 *
 * @param serverAddress
 *        - address of the agent we want to connect to.
 * @param webSocketPort
 *        - the port number, on which the Server is listening
 * @param agentId
 *        - An identifier of the current agent
 * @throws URISyntaxException
 *         - thrown to indicate that a string could not be parsed as a URI reference
 * @throws IOException
 *         - thrown when I/O exception of some sort has occurred
 * @throws DeploymentException
 *         - failure to publish an endpoint on its server, or a failure to connect a client to its server
 */
public void connectToServer(String serverAddress, int webSocketPort, String agentId)
    throws DeploymentException,
        IOException,
        URISyntaxException {
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    container.setDefaultMaxTextMessageBufferSize(Integer.MAX_VALUE);
    String uriAddress = String.format(SERVER_URI, serverAddress, webSocketPort);
    this.session = container.connectToServer(AgentEndpoint.class, new URI(uriAddress));

    List<DeviceInformation> connectedDevicesInformation = deviceManager.getDevicesInformation();
    DeviceInformation[] devicesInformationArray = connectedDevicesInformation.toArray(new DeviceInformation[0]);

    RequestMessage registerAgentRequest = new RequestMessage(MessageAction.REGISTER_AGENT,
                                                             agentId,
                                                             devicesInformationArray);

    String registerAgentJsonRequest = jsonUtil.serialize(registerAgentRequest);
    sendText(registerAgentJsonRequest, session);

    LOGGER.debug("Connected to server address: " + uriAddress);

    agentManager.registerServer();
    LOGGER.info("The Server(" + serverAddress + ":" + webSocketPort
            + ") is registered for the device changed event notifications.");
}
 
开发者ID:MusalaSoft,项目名称:atmosphere-agent,代码行数:42,代码来源:AgentDispatcher.java

示例8: webSocketsStatusTest

import javax.websocket.WebSocketContainer; //导入方法依赖的package包/类
/**
 * Ensures that CDI event is relayed over the webSocket status endpoint.
 *
 * @throws Exception when the test has failed
 */
@Test
public void webSocketsStatusTest() throws Exception {
    //given
    UUID uuid = UUID.randomUUID();
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    URI uri = UriBuilder.fromUri(deploymentUrl).scheme("ws").path("status").path(uuid.toString()).build();
    container.connectToServer(endpoint, uri);

    //when
    Thread.sleep(200);
    testEvent.fire(new StatusMessageEvent(uuid, StatusMessage.GITHUB_CREATE,
                                          singletonMap(EXTRA_DATA_KEY, "http://github.com/dummy-project-location")));
    endpoint.getLatch().await(1, TimeUnit.SECONDS);

    //then
    assertNotNull("a status message should have been send", endpoint.getMessage());
    assertTrue(endpoint.getMessage().contains(EXTRA_DATA_KEY));
}
 
开发者ID:fabric8-launcher,项目名称:launchpad-missioncontrol,代码行数:24,代码来源:MissionControlStatusEndpointIT.java

示例9: WebsocketClientEndpoint

import javax.websocket.WebSocketContainer; //导入方法依赖的package包/类
/**
 * constructor
 * 
 * @param endpointURI
 */
public WebsocketClientEndpoint(URI endpointURI, IwsSessionNotifier sessionNotifier) {
	try {
		this.sessionNotifier = sessionNotifier;
		System.out.println("WebsocketClientEndpoint.WebsocketClientEndpoint(): creating WebSocketContainer...");
		WebSocketContainer container = ContainerProvider.getWebSocketContainer();
		container.connectToServer(this, endpointURI);
	} catch (Exception e) {
		System.out.println(
				"WebsocketClientEndpoint.WebsocketClientEndpoint(): ERROR: Exception on container connectToServer, reason: "
						+ e.getMessage());
		//throw new RuntimeException(e);
       	//notify initiate failed
       	this.sessionNotifier.notifyWsInitiateFailed();
	}
}
 
开发者ID:instruritesh,项目名称:ZStreamingQuote,代码行数:21,代码来源:WebsocketClientEndpoint.java

示例10: connect

import javax.websocket.WebSocketContainer; //导入方法依赖的package包/类
public static void connect(String clientString) throws IOException {
	if (clientString.startsWith(NEW_CLIENT) ) {
		clientString = clientString.substring(NEW_CLIENT.length());

		WebSocketContainer c = ContainerProvider.getWebSocketContainer();
		Hello.log(AnnotatedClientEndpoint.class, "Starting the client for " + clientString);

		URI uriServerEP = URI.create(clientString);
		try {
			Session s = c.connectToServer(AnnotatedClientEndpoint.class, uriServerEP);

			// we're just going to maintain one client at a time, so reading the output
			// can be somewhat sane.. Set the new session, and close the old one.
			s = clientConnection.getAndSet(s);
			if ( s != null )
				s.close();
		} catch (DeploymentException e) {
			e.printStackTrace();
		}
	}
}
 
开发者ID:WASdev,项目名称:sample.async.websockets,代码行数:22,代码来源:AnnotatedClientEndpoint.java

示例11: sendMessage

import javax.websocket.WebSocketContainer; //导入方法依赖的package包/类
/**
 * Sends message to the WebSocket server.
 *
 * @param endpoint The server endpoint
 * @param msg The message
 * @return a return message
 */
private String sendMessage(String endpoint, String msg) {

    LOGGER.config(() -> "Sending message: " + msg);

    String returnValue = "-1";
    try {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        String uri = serviceUrl + endpoint;
        Session session = container.connectToServer(this, URI.create(uri));
        session.getBasicRemote().sendText(msg != null ? msg : "");
        returnValue = session.getId();

    } catch (DeploymentException | IOException ex) {
        LOGGER.warning(ex.getMessage());
    }

    return returnValue;
}
 
开发者ID:ivargrimstad,项目名称:snoop,代码行数:26,代码来源:SnoopRegistrationClient.java

示例12: connect

import javax.websocket.WebSocketContainer; //导入方法依赖的package包/类
@Override
public void connect() throws DeploymentException, IOException {
    ConnectionDetails details = info.getConnectionDetails();
    Log.log(Level.FINE, drain, "Creating websocket to {0}", details.getTarget());

    URI uriServerEP = URI.create(details.getTarget());

    authConfigurator = new GameOnHeaderAuthConfigurator(details.getToken(), uriServerEP.getRawPath());
    final ClientEndpointConfig cec = ClientEndpointConfig.Builder.create()
            .decoders(Arrays.asList(RoutedMessageDecoder.class)).encoders(Arrays.asList(RoutedMessageEncoder.class))
            .configurator(authConfigurator)
            .build();

    WebSocketContainer c = ContainerProvider.getWebSocketContainer();
    this.session = c.connectToServer(this, cec, uriServerEP);
}
 
开发者ID:gameontext,项目名称:gameon-mediator,代码行数:17,代码来源:WebSocketClientConnection.java

示例13: createAndGetSession

import javax.websocket.WebSocketContainer; //导入方法依赖的package包/类
/**
 * Create session
 *
 * @param jsessionid
 * @param userpwd
 * @return
 */
protected Session createAndGetSession(String jsessionid, String userpwd) {
	WebSocketContainer container = ContainerProvider.getWebSocketContainer();
	try {
		StringBuilder sb = new StringBuilder("ws://localhost:");
		sb.append(PORT).append(Constants.SLASH).append(CTXPATH).append(Constants.SLASH).append("ocelot-endpoint");
		URI uri = new URI(sb.toString());
		return container.connectToServer(new Endpoint() {
			@Override
			public void onOpen(Session session, EndpointConfig config) {
			}
		}, createClientEndpointConfigWithJsession(jsessionid, userpwd), uri);
	} catch (URISyntaxException | DeploymentException | IOException ex) {
		ex.getCause().printStackTrace();
		fail("CONNEXION FAILED " + ex.getMessage());
	}
	return null;
}
 
开发者ID:ocelotds,项目名称:ocelot,代码行数:25,代码来源:AbstractOcelotTest.java

示例14: testConnectToServerEndpointInvalidScheme

import javax.websocket.WebSocketContainer; //导入方法依赖的package包/类
@Test(expected=javax.websocket.DeploymentException.class)
public void testConnectToServerEndpointInvalidScheme() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // Must have a real docBase - just use temp
    Context ctx =
        tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    wsContainer.connectToServer(TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ftp://localhost:" + getPort() +
                    TesterEchoServer.Config.PATH_ASYNC));
}
 
开发者ID:sdw2330976,项目名称:apache-tomcat-7.0.57,代码行数:18,代码来源:TestWsWebSocketContainer.java

示例15: testConnectToServerEndpointNoHost

import javax.websocket.WebSocketContainer; //导入方法依赖的package包/类
@Test(expected=javax.websocket.DeploymentException.class)
public void testConnectToServerEndpointNoHost() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // Must have a real docBase - just use temp
    Context ctx =
        tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    wsContainer.connectToServer(TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://" + TesterEchoServer.Config.PATH_ASYNC));
}
 
开发者ID:sdw2330976,项目名称:apache-tomcat-7.0.57,代码行数:17,代码来源:TestWsWebSocketContainer.java


注:本文中的javax.websocket.WebSocketContainer.connectToServer方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。