Java Code Examples for org.eclipse.jetty.websocket.client.WebSocketClient

The following are top voted examples for showing how to use org.eclipse.jetty.websocket.client.WebSocketClient. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: diozero   File: JsonWebSocketProtocolHandler.java   View source code 9 votes vote down vote up
public JsonWebSocketProtocolHandler(NativeDeviceFactoryInterface deviceFactory) {
	super(deviceFactory);

	serialiser = GSON::toJson;
	deserialiser = GSON::fromJson;
	
	webSocketClient = new WebSocketClient();
	try {
		webSocketClient.start();

		URI uri = new URI("ws://localhost:8080/diozero");
		Logger.debug("Connecting to: {}...", uri);
		session = webSocketClient.connect(this, uri, new ClientUpgradeRequest()).get();
		Logger.debug("Connected to: {}", uri);
	} catch (Exception e) {
		throw new RuntimeIOException(e);
	}
}
 
Example 2
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: LiveReloadServerTests.java   View source code 6 votes vote down vote up
@Test
public void triggerReload() throws Exception {
	WebSocketClient client = new WebSocketClient();
	try {
		Socket socket = openSocket(client, new Socket());
		this.server.triggerReload();
		Thread.sleep(500);
		this.server.stop();
		assertThat(socket.getMessages(0))
				.contains("http://livereload.com/protocols/official-7");
		assertThat(socket.getMessages(1)).contains("command\":\"reload\"");
	}
	finally {
		client.stop();
	}
}
 
Example 3
Project: spring-boot-concourse   File: LiveReloadServerTests.java   View source code 6 votes vote down vote up
@Test
public void triggerReload() throws Exception {
	WebSocketClient client = new WebSocketClient();
	try {
		Socket socket = openSocket(client, new Socket());
		this.server.triggerReload();
		Thread.sleep(500);
		this.server.stop();
		assertThat(socket.getMessages(0))
				.contains("http://livereload.com/protocols/official-7");
		assertThat(socket.getMessages(1)).contains("command\":\"reload\"");
	}
	finally {
		client.stop();
	}
}
 
Example 4
Project: sqlsocket   File: WebSocketTester.java   View source code 6 votes vote down vote up
@Test
public void connect() throws Exception {
   final WebSocketClient client = new WebSocketClient();

   client.start();

   final WebSocketAdapter socket = new WebSocketAdapter() {
      @Override
      public void onWebSocketConnect(Session session) {
         session.getRemote().sendStringByFuture("yo man!");

         session.close();
      }
   };

   client.connect(
      socket,
      URI.create("ws://localhost:8080/ws/"),
      new ClientUpgradeRequest()
   );

   Thread.sleep(1000L);

   client.stop();
}
 
Example 5
Project: contestparser   File: LiveReloadServerTests.java   View source code 6 votes vote down vote up
@Test
public void triggerReload() throws Exception {
	WebSocketClient client = new WebSocketClient();
	try {
		Socket socket = openSocket(client, new Socket());
		this.server.triggerReload();
		Thread.sleep(500);
		this.server.stop();
		assertThat(socket.getMessages(0),
				containsString("http://livereload.com/protocols/official-7"));
		assertThat(socket.getMessages(1), containsString("command\":\"reload\""));
	}
	finally {
		client.stop();
	}
}
 
Example 6
Project: maker   File: SimpleEchoClient.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
    String destUri = "ws://192.168.100.78:2014";
    if (args.length > 0) {
        destUri = args[0];
    }
    WebSocketClient client = new WebSocketClient();
    SimpleEchoSocket socket = new SimpleEchoSocket();
    try {
        client.start();
        URI echoUri = new URI(destUri);
        ClientUpgradeRequest request = new ClientUpgradeRequest();
        client.connect(socket, echoUri, request);
        System.out.printf("Connecting to : %s%n", echoUri);
        socket.awaitClose(5, TimeUnit.SECONDS);
    } catch (Throwable t) {
        t.printStackTrace();
    } finally {
        try {
            client.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
Example 7
Project: java_rosbridge   File: RosBridge.java   View source code 6 votes vote down vote up
/**
 * Connects to the Rosbridge host at the provided URI.
 * @param rosBridgeURI the URI to the ROS Bridge websocket server. Note that ROS Bridge by default uses port 9090. An example URI is: ws://localhost:9090
 * @param waitForConnection if true, then this method will block until the connection is established. If false, then return immediately.
 */
public void connect(String rosBridgeURI, boolean waitForConnection){
	WebSocketClient client = new WebSocketClient();
	try {
		client.start();
		URI echoUri = new URI(rosBridgeURI);
		ClientUpgradeRequest request = new ClientUpgradeRequest();
		client.connect(this, echoUri, request);
		System.out.printf("Connecting to : %s%n", echoUri);
		if(waitForConnection){
			this.waitForConnection();
		}

	} catch (Throwable t) {
		t.printStackTrace();
	}

}
 
Example 8
Project: java_rosbridge   File: SimpleEchoClient.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
	String destUri = "ws://echo.websocket.org";
	if (args.length > 0) {
		destUri = args[0];
	}
	WebSocketClient client = new WebSocketClient();
	SimpleEchoSocket socket = new SimpleEchoSocket();
	try {
		client.start();
		URI echoUri = new URI(destUri);
		ClientUpgradeRequest request = new ClientUpgradeRequest();
		client.connect(socket, echoUri, request);
		System.out.printf("Connecting to : %s%n", echoUri);
		socket.awaitClose(15, TimeUnit.SECONDS);
	} catch (Throwable t) {
		t.printStackTrace();
	} finally {
		try {
			client.stop();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
 
Example 9
Project: cloud-bigtable-examples   File: CoinbaseSocket.java   View source code 6 votes vote down vote up
@Override
public boolean start() throws IOException {
  String destUri = "wss://ws-feed.exchange.coinbase.com";
  WebSocketClient client = new WebSocketClient(new SslContextFactory());
  try {
    LOG.info("connecting to coinbsae feed");
    client.start();
    URI echoUri = new URI(destUri);
    ClientUpgradeRequest request = new ClientUpgradeRequest();
    client.connect(this, echoUri, request);
    LOG.info("done connecting");
  } catch (Throwable t) {
    t.printStackTrace();
  }
  return advance();
}
 
Example 10
Project: stream-analyzer   File: WebtrendsStreamListenerActor.java   View source code 6 votes vote down vote up
/**
 * Establishes a connection with the webtrends stream api
 * @see akka.actor.UntypedActor#preStart()
 */
public void preStart() throws Exception {
			
	// initialize the uuid generator which is based on time and ethernet address
	this.uuidGenerator = Generators.timeBasedGenerator(EthernetAddress.fromInterface());
	
	// authenticate with the webtrends service
	WebtrendsTokenRequest tokenRequest = new WebtrendsTokenRequest(this.authUrl, this.authAudience, this.authScope, this.clientId, this.clientSecret);
	this.oAuthToken = tokenRequest.execute();		
	
	// initialize the webtrends stream socket client and connect the listener
	this.webtrendsStreamSocketClient = new WebSocketClient();
	try {
		this.webtrendsStreamSocketClient.start();
		ClientUpgradeRequest upgradeRequest = new ClientUpgradeRequest();
		this.webtrendsStreamSocketClient.connect(this, new URI(this.eventStreamUrl), upgradeRequest);
		await(5, TimeUnit.SECONDS);
	} catch(Exception e) {
		throw new RuntimeException("Unable to connect to web socket: " + e.getMessage(), e);
	}
	
	this.componentRegistryRef.tell(new ComponentRegistrationMessage(EVENT_SOURCE_ID, ComponentType.STREAM_LISTENER, getSelf()), getSelf());
}
 
Example 11
Project: reactiveBTC   File: TailTrades.java   View source code 6 votes vote down vote up
private void notifyWebSockets(final String data) {
    URI uri = URI.create("ws://localhost:8080/trades/");

    WebSocketClient client = new WebSocketClient();
    try {
        try {
            client.start();
            // The socket that receives events
            TradeSocket socket = new TradeSocket();
            // Attempt Connect
            Future<Session> fut = client.connect(socket, uri);
            // Wait for Connect
            Session session = fut.get();
            // Send a message
            session.getRemote().sendString(data);
            // Close session
            session.close();
        } finally {
            client.stop();
        }
    } catch (Throwable t) {
        //t.printStackTrace(System.err);
    }
}
 
Example 12
Project: dawnsci   File: RemoteDataset.java   View source code 6 votes vote down vote up
private void createFileListener() throws Exception {
	
       URI uri = URI.create(urlBuilder.getEventURL());

       this.client = new WebSocketClient(exec);
       client.start();
      
       final DataEventSocket clientSocket = new DataEventSocket();
       // Attempt Connect
       Future<Session> fut = client.connect(clientSocket, uri);

       // Wait for Connect
       connection = fut.get();

       // Send a message
       connection.getRemote().sendString("Connected to "+urlBuilder.getPath());
}
 
Example 13
Project: roboconf-platform   File: HttpAgentClient.java   View source code 6 votes vote down vote up
@Override
public void openConnection() throws IOException {

	this.logger.info( getId() + " is opening a connection to the DM." );
	try {
		this.client = new WebSocketClient();
		this.socket = new AgentWebSocket( this.messageQueue );
		this.client.start();

		URI dmUri = new URI( "ws://" + this.dmIp + ":" + this.dmPort + HttpConstants.DM_SOCKET_PATH );
		this.logger.fine( "Connecting to " + dmUri );
		ClientUpgradeRequest request = new ClientUpgradeRequest();

		Future<Session> fut = this.client.connect( this.socket, dmUri, request );
		this.clientSession = fut.get();

	} catch( Exception e ) {
		throw new IOException( e );
	}
}
 
Example 14
Project: webtrends-kafka-producer   File: WebtrendsStreamListenerActor.java   View source code 6 votes vote down vote up
/**
 * Establishes a connection with the webtrends stream api
 * @see akka.actor.UntypedActor#preStart()
 */
public void preStart() throws Exception {
	
	// authenticate with the webtrends service
	WebtrendsTokenRequest tokenRequest = new WebtrendsTokenRequest(this.authUrl, this.authAudience, this.authScope, this.clientId, this.clientSecret);
	this.oAuthToken = tokenRequest.execute();		
	
	// initialize the webtrends stream socket client and connect the listener
	this.webtrendsStreamSocketClient = new WebSocketClient();
	try {
		this.webtrendsStreamSocketClient.start();
		ClientUpgradeRequest upgradeRequest = new ClientUpgradeRequest();
		this.webtrendsStreamSocketClient.connect(this, new URI(this.eventStreamUrl), upgradeRequest);
		await(5, TimeUnit.SECONDS);
	} catch(Exception e) {
		throw new RuntimeException("Unable to connect to web socket: " + e.getMessage(), e);
	}		
}
 
Example 15
Project: HexScape   File: ClientNetwork.java   View source code 6 votes vote down vote up
public void connect(User user, String url) {
if (socket == null) {
	String destUri = "ws://" + url;
	client = new WebSocketClient();
	
	client.getPolicy().setMaxTextMessageSize(1000000);
	socket = new ClientWebSocket(user);
	try {
		client.start();
		URI echoUri = new URI(destUri);
		ClientUpgradeRequest request = new ClientUpgradeRequest();
		client.connect(socket, echoUri, request);
		LOGGER.info("Connecting to : %s%n", echoUri);
		
	} catch (Throwable t) {
		t.printStackTrace();
		client = null;
	}
}
  }
 
Example 16
Project: rasc   File: WebSocketJsonRpcClientFactory.java   View source code 6 votes vote down vote up
@Override
public <T> T create(Class<T> interfaceClass, URL url, String userId,
		String password) {
	final WebSocketClient client = new WebSocketClient();
	clients.add(client);
	try {
		client.start();
		int i = url.getProtocol().equals("http") ? 7 : 8;
		URI uri = new URI("ws://" + url.toString().substring(i));
		Listener listener = new Listener();
		Session session = client.connect(listener, uri).get();
		return interfaceClass.cast(Proxy.newProxyInstance(
				Thread.currentThread().getContextClassLoader(),
				new Class<?>[] { interfaceClass, RequestAttributes.class,
						ResponseAttributes.class, ArrayElementsNotifier.class },
				new WebSocketJsonRpcHandler(session, listener)
				));
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 17
Project: gocd   File: GoAgentServerWebSocketClientBuilder.java   View source code 6 votes vote down vote up
@Override
public WebSocketClient build() throws Exception {
    SslContextFactory sslContextFactory = sslVerificationMode == SslVerificationMode.NONE ? new TrustAllSSLContextFactory() : new SslContextFactory();
    sslContextFactory.setNeedClientAuth(true);

    sslContextFactory.setKeyStore(agentKeystore());
    sslContextFactory.setKeyStorePassword(keystorePassword());
    sslContextFactory.setKeyManagerPassword(keystorePassword());

    if (rootCertFile != null) {
        sslContextFactory.setTrustStore(agentTruststore());
        sslContextFactory.setTrustStorePassword(keystorePassword());
    }

    if (sslVerificationMode == SslVerificationMode.NO_VERIFY_HOST) {
        sslContextFactory.setEndpointIdentificationAlgorithm(null);
    }

    WebSocketClient client = new WebSocketClient(sslContextFactory);
    client.setMaxIdleTimeout(systemEnvironment.getWebsocketMaxIdleTime());
    return client;
}
 
Example 18
Project: buck   File: BuckClient.java   View source code 6 votes vote down vote up
BuckClient(final BuckEventsHandlerInterface buckEventHandler, Project project) {
  mWSClient = new WebSocketClient();
  mProject = project;
  mConnecting = new AtomicBoolean(false);

  mBuckSocket =
      new BuckSocket(
          new BuckEventsHandlerInterface() {
            @Override
            public void onConnect() {
              buckEventHandler.onConnect();
              mConnecting.set(false);
            }

            @Override
            public void onDisconnect() {
              buckEventHandler.onDisconnect();
            }

            @Override
            public void onMessage(String message) {
              buckEventHandler.onMessage(message);
            }
          });
}
 
Example 19
Project: jmeter-bzm-plugins   File: WebSocketConnection.java   View source code 5 votes vote down vote up
public WebSocketConnection(WebSocketClient webSocketClient, String closeConnectionPattern, String encoding) {
	super(encoding);
	this.webSocketClient = webSocketClient;
	this.closeConnectionPattern= new CompoundVariable(closeConnectionPattern).execute();
	initializePatterns();
	this.waitMessage = false;
}
 
Example 20
Project: buabook-api-interface   File: BuaBookApiWebSocket.java   View source code 5 votes vote down vote up
public BuaBookApiWebSocket(String wsUrl, BuaBookApiAccess apiAccess, QueuedThreadPool webSocketThreadPool) throws Exception {
	if(Strings.isNullOrEmpty(wsUrl) || apiAccess == null)
		throw new IllegalArgumentException("Must supply WebSocket URL and connection object");
	
	this.webSocketUrl = wsUrl;
	this.apiAccess = apiAccess;
	
	this.webSocketClient = new WebSocketClient(new SslContextFactory(), webSocketThreadPool);
	this.webSocketClient.setMaxIdleTimeout(WS_IDLE_TIMEOUT_MS);
	this.webSocketClient.start();
}
 
Example 21
Project: MeMezBots-Dev   File: OK.java   View source code 5 votes vote down vote up
public void LOLOLOL(){
 System.out.println( "Hello World!" );
    String dest = "ws://localhost:8080/jsr356toUpper";
            WebSocketClient client = new WebSocketClient();
            try {
                 
                ToUpperClientSocket socket = new ToUpperClientSocket();
                client.start();
                URI echoUri = new URI(dest);
                ClientUpgradeRequest request = new ClientUpgradeRequest();
                client.connect(socket, echoUri, request);
                socket.getLatch().await();
                ByteBuffer buf = ByteBuffer.allocate(5);
                buf.put(0, (byte)254);
                buf.order(ByteOrder.LITTLE_ENDIAN);
                buf.putInt(1, 5);
                socket.sendMessage(buf);
                Thread.sleep(10000l);
                String name = "BadPlayer";
                ByteBuffer buf1 = ByteBuffer.allocate(1 + 2*name.length());
                buf1.put(0, (byte)0);
                for (int i=0;i<name.length();i++) {
                	buf1.order(ByteOrder.LITTLE_ENDIAN);
                    buf.putShort(1 + i*2 ,(short)name.charAt(i));
                }
     
            } catch (Throwable t) {
                t.printStackTrace();
            } finally {
                try {
                    client.stop();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

}
 
Example 22
Project: org.openhab.binding.loxone   File: LxWsClient.java   View source code 5 votes vote down vote up
/**
 * Connect the websocket.
 * Attempts to connect to the websocket on a remote Miniserver.
 *
 * @return
 *         true if connection request initiated correctly, false if not
 */
boolean connect() {
    logger.trace("[{}] connect() websocket", debugId);
    if (state != ClientState.IDLE) {
        close("Attempt to connect a websocket in non-idle state: " + state);
        return false;
    }

    synchronized (state) {
        socket = new LxWebSocket();
        wsClient = new WebSocketClient();

        try {
            wsClient.start();

            URI target = new URI("ws://" + host.getHostAddress() + ":" + port + SOCKET_URL);
            ClientUpgradeRequest request = new ClientUpgradeRequest();
            request.setSubProtocols("remotecontrol");

            wsClient.connect(socket, target, request);
            setClientState(ClientState.CONNECTING);
            startResponseTimeout();

            logger.debug("[{}] Connecting to server : {} ", debugId, target);
            return true;

        } catch (Exception e) {
            setClientState(ClientState.IDLE);
            close("Connection to websocket failed : " + e.getMessage());
            return false;
        }
    }
}
 
Example 23
Project: TwitchMessenger   File: TwitchMessenger.java   View source code 5 votes vote down vote up
public void connect() throws Exception {
    ClientUpgradeRequest request = new ClientUpgradeRequest();
    request.setHeader("Cookie", "CurseAuthToken=" + URLEncoder.encode(getAuthToken()));
    WebSocketClient client = new WebSocketClient(new SslContextFactory());
    TwitchNotificationSocket socket = new TwitchNotificationSocket(this);
    client.start();
    URI destUri = new URI("wss://notifications-eu-v1.curseapp.net/");
    System.out.println("Connecting to " + destUri);
    client.connect(socket, destUri, request);
}
 
Example 24
Project: webframework   File: WebSocketsTest.java   View source code 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
	AppUtil.startLogging(args, 1);
	final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger("org.eclipse.jetty");
	if (!(logger instanceof ch.qos.logback.classic.Logger)) {
		return;
	}
	ch.qos.logback.classic.Logger logbackLogger = (ch.qos.logback.classic.Logger) logger;
	logbackLogger.setLevel(ch.qos.logback.classic.Level.INFO);

	final int serverPort = (args.length > 0) ? Integer.parseInt(args[0]) : DEFAULT_SERVER_PORT;
	final String destUri = "ws://localhost:" + Integer.toString(serverPort) + "/test";

	final SocketTestServer socketServer = new SocketTestServer();
	final SessionHandler sessionHandler = new SimpleSessionHandler(socketServer, new ServletSessionStore());
	final RequestHandler handler = new RequestHandler(null, sessionHandler);
	final Server server = new Server(serverPort);
	final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
	context.setContextPath("/");
	server.setHandler(context);
	context.addServlet(new ServletHolder(new EmbeddedServlet(handler)), "/*");

	server.start();
	System.out.println("Server started");

	Thread.sleep(10000);

	// Start Client
	final WebSocketClient client = new WebSocketClient();
	final SocketTestClient socket = new SocketTestClient();

	client.start();
	final URI uri = new URI(destUri);
	final ClientUpgradeRequest request = new ClientUpgradeRequest();
	System.out.printf("Connecting to : %s%n", uri);

	// wait for closed socket connection.
	socket.awaitClose(5,TimeUnit.SECONDS);
	client.stop();
}
 
Example 25
Project: Offline-Streamer   File: WebSocketTest.java   View source code 5 votes vote down vote up
public void run()
{
    //Set up the connection
    uri = URI.create("ws://187.157.170.85:9000/");
    client = new WebSocketClient();
    connect(client,uri);

}
 
Example 26
Project: incubator-pulsar   File: ProxyAuthenticationTest.java   View source code 5 votes vote down vote up
public void socketTest() throws Exception {
    final String topic = "my-property/use/my-ns/my-topic1";
    final String consumerUri = "ws://localhost:" + port + "/ws/consumer/persistent/" + topic + "/my-sub";
    final String producerUri = "ws://localhost:" + port + "/ws/producer/persistent/" + topic;
    URI consumeUri = URI.create(consumerUri);
    URI produceUri = URI.create(producerUri);

    consumeClient = new WebSocketClient();
    SimpleConsumerSocket consumeSocket = new SimpleConsumerSocket();
    produceClient = new WebSocketClient();
    SimpleProducerSocket produceSocket = new SimpleProducerSocket();

    consumeClient.start();
    ClientUpgradeRequest consumeRequest = new ClientUpgradeRequest();
    Future<Session> consumerFuture = consumeClient.connect(consumeSocket, consumeUri, consumeRequest);
    log.info("Connecting to : {}", consumeUri);

    ClientUpgradeRequest produceRequest = new ClientUpgradeRequest();
    produceClient.start();
    Future<Session> producerFuture = produceClient.connect(produceSocket, produceUri, produceRequest);
    Assert.assertTrue(consumerFuture.get().isOpen());
    Assert.assertTrue(producerFuture.get().isOpen());

    consumeSocket.awaitClose(1, TimeUnit.SECONDS);
    produceSocket.awaitClose(1, TimeUnit.SECONDS);
    Assert.assertTrue(produceSocket.getBuffer().size() > 0);
    Assert.assertEquals(produceSocket.getBuffer(), consumeSocket.getBuffer());
}
 
Example 27
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: LiveReloadServerTests.java   View source code 5 votes vote down vote up
@Test
public void pingPong() throws Exception {
	WebSocketClient client = new WebSocketClient();
	try {
		Socket socket = new Socket();
		Driver driver = openSocket(client, new Driver(socket));
		socket.getRemote().sendPing(NO_DATA);
		Thread.sleep(200);
		this.server.stop();
		assertThat(driver.getPongCount()).isEqualTo(1);
	}
	finally {
		client.stop();
	}
}
 
Example 28
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: LiveReloadServerTests.java   View source code 5 votes vote down vote up
@Test
public void clientClose() throws Exception {
	WebSocketClient client = new WebSocketClient();
	try {
		Socket socket = openSocket(client, new Socket());
		socket.getSession().close();
	}
	finally {
		client.stop();
	}
	awaitClosedException();
	assertThat(this.server.getClosedExceptions().size()).isGreaterThan(0);
}
 
Example 29
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: LiveReloadServerTests.java   View source code 5 votes vote down vote up
@Test
public void serverClose() throws Exception {
	WebSocketClient client = new WebSocketClient();
	try {
		Socket socket = openSocket(client, new Socket());
		Thread.sleep(200);
		this.server.stop();
		Thread.sleep(200);
		assertThat(socket.getCloseStatus()).isEqualTo(1006);
	}
	finally {
		client.stop();
	}
}
 
Example 30
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: LiveReloadServerTests.java   View source code 5 votes vote down vote up
private <T> T openSocket(WebSocketClient client, T socket) throws Exception,
		URISyntaxException, InterruptedException, ExecutionException, IOException {
	client.start();
	ClientUpgradeRequest request = new ClientUpgradeRequest();
	URI uri = new URI("ws://localhost:" + this.port + "/livereload");
	Session session = client.connect(socket, uri, request).get();
	session.getRemote().sendString(HANDSHAKE);
	Thread.sleep(200);
	return socket;
}
 
Example 31
Project: diozero   File: ProtobufWebSocketProtocolHandler.java   View source code 5 votes vote down vote up
public ProtobufWebSocketProtocolHandler(NativeDeviceFactoryInterface deviceFactory) {
	super(deviceFactory);

	webSocketClient = new WebSocketClient();
	try {
		webSocketClient.start();

		URI uri = new URI("ws://localhost:8080/diozero");
		Logger.debug("Connecting to: {}...", uri);
		session = webSocketClient.connect(this, uri, new ClientUpgradeRequest()).get();
		Logger.debug("Connected to: {}", uri);
	} catch (Exception e) {
		throw new RuntimeIOException(e);
	}
}
 
Example 32
Project: spring-boot-concourse   File: LiveReloadServerTests.java   View source code 5 votes vote down vote up
@Test
public void pingPong() throws Exception {
	WebSocketClient client = new WebSocketClient();
	try {
		Socket socket = new Socket();
		Driver driver = openSocket(client, new Driver(socket));
		socket.getRemote().sendPing(NO_DATA);
		Thread.sleep(200);
		this.server.stop();
		assertThat(driver.getPongCount()).isEqualTo(1);
	}
	finally {
		client.stop();
	}
}
 
Example 33
Project: spring-boot-concourse   File: LiveReloadServerTests.java   View source code 5 votes vote down vote up
@Test
public void clientClose() throws Exception {
	WebSocketClient client = new WebSocketClient();
	try {
		Socket socket = openSocket(client, new Socket());
		socket.getSession().close();
	}
	finally {
		client.stop();
	}
	awaitClosedException();
	assertThat(this.server.getClosedExceptions().size()).isGreaterThan(0);
}
 
Example 34
Project: spring-boot-concourse   File: LiveReloadServerTests.java   View source code 5 votes vote down vote up
@Test
public void serverClose() throws Exception {
	WebSocketClient client = new WebSocketClient();
	try {
		Socket socket = openSocket(client, new Socket());
		Thread.sleep(200);
		this.server.stop();
		Thread.sleep(200);
		assertThat(socket.getCloseStatus()).isEqualTo(1006);
	}
	finally {
		client.stop();
	}
}
 
Example 35
Project: spring-boot-concourse   File: LiveReloadServerTests.java   View source code 5 votes vote down vote up
private <T> T openSocket(WebSocketClient client, T socket) throws Exception,
		URISyntaxException, InterruptedException, ExecutionException, IOException {
	client.start();
	ClientUpgradeRequest request = new ClientUpgradeRequest();
	URI uri = new URI("ws://localhost:" + this.port + "/livereload");
	Session session = client.connect(socket, uri, request).get();
	session.getRemote().sendString(HANDSHAKE);
	Thread.sleep(200);
	return socket;
}
 
Example 36
Project: contestparser   File: LiveReloadServerTests.java   View source code 5 votes vote down vote up
@Test
public void pingPong() throws Exception {
	WebSocketClient client = new WebSocketClient();
	try {
		Socket socket = new Socket();
		Driver driver = openSocket(client, new Driver(socket));
		socket.getRemote().sendPing(NO_DATA);
		Thread.sleep(200);
		this.server.stop();
		assertThat(driver.getPongCount(), equalTo(1));
	}
	finally {
		client.stop();
	}
}
 
Example 37
Project: contestparser   File: LiveReloadServerTests.java   View source code 5 votes vote down vote up
@Test
public void clientClose() throws Exception {
	WebSocketClient client = new WebSocketClient();
	try {
		Socket socket = openSocket(client, new Socket());
		socket.getSession().close();
	}
	finally {
		client.stop();
	}
	awaitClosedException();
	assertThat(this.server.getClosedExceptions().size(), greaterThan(0));
}
 
Example 38
Project: contestparser   File: LiveReloadServerTests.java   View source code 5 votes vote down vote up
@Test
public void serverClose() throws Exception {
	WebSocketClient client = new WebSocketClient();
	try {
		Socket socket = openSocket(client, new Socket());
		Thread.sleep(200);
		this.server.stop();
		Thread.sleep(200);
		assertThat(socket.getCloseStatus(), equalTo(1006));
	}
	finally {
		client.stop();
	}
}
 
Example 39
Project: contestparser   File: LiveReloadServerTests.java   View source code 5 votes vote down vote up
private <T> T openSocket(WebSocketClient client, T socket) throws Exception,
		URISyntaxException, InterruptedException, ExecutionException, IOException {
	client.start();
	ClientUpgradeRequest request = new ClientUpgradeRequest();
	URI uri = new URI("ws://localhost:" + this.port + "/livereload");
	Session session = client.connect(socket, uri, request).get();
	session.getRemote().sendString(HANDSHAKE);
	Thread.sleep(200);
	return socket;
}
 
Example 40
Project: JMeter-WebSocket-StompSampler   File: ServiceSocket.java   View source code 5 votes vote down vote up
public ServiceSocket(WebSocketSampler parent, WebSocketClient client) {
	this.parent = parent;
	this.client = client;

	//Evaluate response matching patterns in case thay contain JMeter variables (i.e. ${var})
	connectPattern = new CompoundVariable(parent.getConnectPattern()).execute();
	subscribePattern = new CompoundVariable(parent.getSubscribePattern()).execute();
	disconnectPattern = new CompoundVariable(parent.getCloseConncectionPattern()).execute();
	logMessage.append("\n\n[Execution Flow]\n");
	logMessage.append(" - Opening new connection\n");
	initializePatterns();
}