FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Web Socket - Jetty by averikitsch · Pull Request #1282 · GoogleCloudPlatform/java-docs-samples · GitHub

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .java  (4) .jsp  (2) .md  (1) .xml  (1) .yaml  (1) All 5 file types selected
Only manifest files
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
    • README.md
    • pom.xml
        • app.yaml
        • ClientSocket.java
        • EchoServlet.java
        • SendServlet.java
        • ServerSocket.java
        • index.jsp
        • js_client.jsp
62 changes: 62 additions & 0 deletions appengine-java8/websocket-jetty/README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# 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 [native Jetty WebSocket Server API](http://www.eclipse.org/jetty/documentation/9.4.x/jetty-websocket-server-api.html) to create a server-side socket
and the [native Jetty WebSocket Client API](http://www.eclipse.org/jetty/documentation/9.4.x/jetty-websocket-client-api.html).

## 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`

Note: This application constructs a Web Socket URL using `getWebSocketAddress`
in the [SendServlet Class](src/main/java/com/example/flexible/websocket/jettynative/SendServlet.java)
. The application assumes the latest version of the service.
92 changes: 92 additions & 0 deletions appengine-java8/websocket-jetty/pom.xml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<!--
Copyright 2018 Google LLC

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 xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.eclipse.jetty.demo</groupId>
<artifactId>native-jetty-websocket-example</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<!--
The parent pom defines common style checks and testing strategies for our samples.
Removing or replacing it should not effect the execution of the samples in anyway.
-->
<parent>
<groupId>com.google.cloud.samples</groupId>
<artifactId>shared-configuration</artifactId>
<version>1.0.10</version>
</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>
<!-- To run websockets client -->
<dependency>
<groupId>org.eclipse.jetty.websocket</groupId>
<artifactId>websocket-client</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.websocket</groupId>
<artifactId>websocket-servlet</artifactId>
<version>${jetty.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Copyright 2018 Google LLC
#
# 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* Copyright 2018 Google LLC
*
* 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.jettynative;

import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.logging.Logger;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;

/**
* Basic Echo Client Socket.
*/
@WebSocket(maxTextMessageSize = 64 * 1024)
public class ClientSocket {
private Logger logger = Logger.getLogger(ClientSocket.class.getName());
private Session session;
// 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<>();

@OnWebSocketClose
public void onClose(int statusCode, String reason) {
logger.fine("Connection closed: " + statusCode + ":" + reason);
this.session = null;
}

@OnWebSocketConnect
public void onConnect(Session session) {
this.session = session;
}

@OnWebSocketMessage
public void onMessage(String msg) {
logger.fine("Message Received : " + msg);
messages.add(msg);
}

// Retrieve all received messages.
public static Collection<String> getReceivedMessages() {
return Collections.unmodifiableCollection(messages);
}
}
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* Copyright 2018 Google LLC
*
* 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.jettynative;

import javax.servlet.annotation.WebServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;

/*
* Server-side WebSocket registered as /echo servlet.
*/
@SuppressWarnings("serial")
@WebServlet(name = "Echo WebSocket Servlet", urlPatterns = { "/echo" })
public class EchoServlet extends WebSocketServlet {
@Override
public void configure(WebSocketServletFactory factory) {
factory.register(ServerSocket.class);
}
}
Loading

Back | FazBrowse Home | New Git URL