Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WebSockets samples for Java #1022

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions appengine/websockets/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# App Engine Flexible Environment - Web Socket Example
This sample demonstrates how to use [Websockets](https://tools.ietf.org/html/rfc6455) on [Google App Engine Flexible Environment](https://cloud.google.com/appengine/docs/flexible/java/) using Java.
The sample uses the [JSR-356](https://www.jcp.org/en/jsr/detail?id=356) Java API for the Websocket [client](https://mvnrepository.com/artifact/org.eclipse.jetty.websocket/javax-websocket-client-impl).

## Sample application workflow

1. The sample application creates a server socket using the endpoint `/echo`.
1. The homepage (`/`) provides a form to submit a text message to the server socket. This creates a client-side socket
and sends the message to the server.
1. The server on receiving the message, echoes the message back to the client.
1. The message received by the client is stored in an in-memory cache and is viewable on the homepage.

The sample also provides a Javascript [client](src/main/webapp/js_client.jsp)(`/js_client.jsp`) that you can use to test against the Websocket server.

## Setup

- [Install](https://cloud.google.com/sdk/) and initialize GCloud SDK. This will
```
gcloud init
```
- If this is your first time creating an app engine application
```
gcloud appengine create
```

## Local testing

Run using the [Jetty Maven plugin](http://www.eclipse.org/jetty/documentation/9.4.x/jetty-maven-plugin.html).
```
mvn jetty:run
```
You can then direct your browser to `http://localhost:8080/`

To test the Javascript client, access `http://localhost:8080/js_client.jsp`

## App Engine Flex Deployment

#### `app.yaml` Configuration

App Engine Flex deployment configuration is provided in [app.yaml](src/main/appengine/app.yaml).

Set the environment variable `JETTY_MODULES_ENABLE:websocket` to enable the Jetty websocket module on the Jetty server.

Manual scaling is set to a single instance as we are using an in-memory cache of messages for this sample application.

For more details on configuring your `app.yaml`, please refer to [this resource](https://cloud.google.com/appengine/docs/flexible/nodejs/configuring-your-app-with-app-yaml).

#### Deploy

The sample application is packaged as a war, and hence will be automatically run using the [Java 8/Jetty 9 with Servlet 3.1 Runtime](https://cloud.google.com/appengine/docs/flexible/java/dev-jetty9).

```
mvn appengine:deploy
```
You can then direct your browser to `https://YOUR_PROJECT_ID.appspot.com/`

To test the Javascript client, access `https://YOUR_PROJECT_ID.appspot.com/js_client.jsp`
83 changes: 83 additions & 0 deletions appengine/websockets/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<!--
Copyright 2017 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project>
<modelVersion>4.0.0</modelVersion>
<version>1.0-SNAPSHOT</version>
<groupId>com.example.flexible</groupId>
<artifactId>websocket</artifactId>
<packaging>war</packaging>

<parent>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This parent should be:

  <!--
    The parent pom defines common style checks and testing strategies for our samples.
    Removing or replacing it should not affect the execution of the samples in anyway.
  -->
  <parent>
    <groupId>com.google.cloud.samples</groupId>
    <artifactId>shared-configuration</artifactId>
    <version>1.0.8</version>
  </parent>

<groupId>com.google.cloud</groupId>
<artifactId>appengine-flexible</artifactId>
<version>1.0.0</version>
<relativePath>..</relativePath>
</parent>

<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<failOnMissingWebXml>false</failOnMissingWebXml> <!-- REQUIRED -->
<appengine.maven.plugin>1.3.1</appengine.maven.plugin>
<jetty.version>9.4.4.v20170414</jetty.version>
</properties>

<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<!-- [START maven-websocket-jsr356] -->
<!--Jetty JSR-356 Websocket client side dependency-->
<dependency>
<groupId>org.eclipse.jetty.websocket</groupId>
<artifactId>javax-websocket-client-impl</artifactId>
<version>${jetty.version}</version>
</dependency>
<!-- [END maven-websocket-jsr356] -->
<!--Optional dependency for SettableFuture, see com.example.flexible.websocket.jsr356.ServerSocket -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>20.0</version>
</dependency>
</dependencies>

<build>
<!-- for hot reload of the web application -->
<outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/classes
</outputDirectory>
<plugins>
<!-- for deployment of web application -->
<plugin>
<groupId>com.google.cloud.tools</groupId>
<artifactId>appengine-maven-plugin</artifactId>
<version>${appengine.maven.plugin}</version>
<configuration>
</configuration>
</plugin>
<!-- for local testing of web application -->
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>${jetty.version}</version>
</plugin>
</plugins>
</build>
</project>
34 changes: 34 additions & 0 deletions appengine/websockets/src/main/appengine/app.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

runtime: java
env: flex
manual_scaling:
instances: 1

handlers:
- url: /.*
script: this field is required, but ignored

env_variables:
JETTY_MODULES_ENABLE: websocket


# For applications which can take advantage of session affinity
# (where the load balancer will attempt to route multiple connections from
# the same user to the same App Engine instance), uncomment the folowing:

# network:
# session_affinity: true

Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.flexible.websocket.jsr356;

import com.google.common.util.concurrent.SettableFuture;

import java.net.URI;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ExecutionException;
import java.util.logging.Logger;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

/**
* Web socket client example using JSR-356 Java WebSocket API. Sends a message to the server, and
* stores the echoed messages received from the server.
*/
@ClientEndpoint
public class ClientSocket {

private static final Logger logger = Logger.getLogger(ClientSocket.class.getName());

// stores the messages in-memory.
// Note : this is currently an in-memory store for demonstration,
// not recommended for production use-cases.
private static Collection<String> messages = new ConcurrentLinkedDeque<>();

private SettableFuture<Boolean> future = SettableFuture.create();
private Session session;

ClientSocket(URI endpointUri) {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
session = container.connectToServer(this, endpointUri);
} catch (Exception e) {
throw new RuntimeException(e);
}
}

@OnOpen
public void onOpen(Session session) {
future.set(true);
}

/**
* Handles message received from the server.
* @param message server message in String format
* @param session current session
*/
@OnMessage
public void onMessage(String message, Session session) {
logger.fine("Received message from server : " + message);
messages.add(message);
}

boolean waitOnOpen() throws InterruptedException, ExecutionException {
// wait on handling onOpen
boolean opened = future.get();
logger.fine("Connected to server");
return opened;
}

@OnClose
public void onClose(CloseReason reason, Session session) {
logger.fine("Closing Web Socket: " + reason.getReasonPhrase());
}

void sendMessage(String str) {
try {
// Send a message to the server
logger.fine("Sending message : " + str);
session.getAsyncRemote().sendText(str);
} catch (Exception e) {
logger.severe("Error sending message : " + e.getMessage());
}
}

// Retrieve all received messages.
public static Collection<String> getReceivedMessages() {
return Collections.unmodifiableCollection(messages);
}

@OnError
public void logErrors(Throwable t) {
logger.severe(t.getMessage());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.flexible.websocket.jsr356;

import com.google.common.base.Preconditions;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.logging.Logger;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.HttpStatus;

@WebServlet("/send")
/** Servlet that converts the message sent over POST to be over websocket. */
public class SendServlet extends HttpServlet {

private Logger logger = Logger.getLogger(SendServlet.class.getName());
private final String webSocketAddress = ServerSocket.getWebSocketAddress();
private ClientSocket clientSocket;

private void initializeWebSocket() throws Exception {
clientSocket = new ClientSocket(new URI(webSocketAddress));
clientSocket.waitOnOpen();
logger.info("REST service: open websocket client at " + webSocketAddress);
}

private void sendMessageOverWebSocket(String message) throws Exception {
if (clientSocket == null) {
try {
initializeWebSocket();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
clientSocket.sendMessage(message);
}

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
String message = request.getParameter("message");
Preconditions.checkNotNull(message);
try {
sendMessageOverWebSocket(message);
response.sendRedirect("/");
} catch (Exception e) {
e.printStackTrace(response.getWriter());
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500);
}
}
}
Loading