Skip to content

websocket #473

@kevendra

Description

@kevendra

websocket

I'm working on below sample code, how to use websockets on Google App Engine Flexible Environment with java.
as it mentions in the doc, in order to use websockets on App Engine, we need to connect directly to application instance using the instance's public external IP. This IP can be obtained from the metadata server.
but looks like I'm getting below 403 error when I'm trying to access metadata server

java.io.IOException: Server returned HTTP response code: 403 for URL: http://metadata.google.internal/computeMetadata/v1/instance/network-interfaces/0/access-configs/0/external-ip

Sorry, It's working now, forgot to add Metadata-Flavor header in the request

still, it's worth having spring-websocket sample code, who want to use jGAE with spring websocket

Sample Code

Firewall rule

gcloud compute firewall-rules create default-allow-websockets \
  --allow tcp:65080 \
  --target-tags websocket \
  --description "Allow websocket traffic on port 65080"

app.yaml

runtime: java
env: flex

runtime_config:  # Optional
  jdk: openjdk8
  server: jetty9

handlers:
- url: /.*
  script: this field is required, but ignored
  secure: optional # always never optional # Require HTTPS

manual_scaling:
  instances: 1

network:
  forwarded_ports:
  - 65080
  instance_tag: websocket
  private static final int DEFAULT_PORT = 65080;
  private static final String NETWORK_INTERFACE_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/network-interfaces/0/access-configs/0/" + "external-ip";

  private String getHostname() throws IOException {
	  String hostname = "localhost";
//      if (SystemProperty.environment.value().equals(SystemProperty.Environment.Value.Production)) {
        URL url = new URL(NETWORK_INTERFACE_METADATA_URL);
        HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
        httpUrlConnection.setRequestProperty("Metadata-Flavor", "Google");
//        httpUrlConnection.setRequestProperty("X-Google-Metadata-Request", "true");
        InputStream in = httpUrlConnection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String result, line = reader.readLine();
        result = line;
        while ((line = reader.readLine()) != null) {
          result += line;
        }
        hostname = result;
//      }
    return hostname;
  }

  /**
   * @return a Websocket URL of this server.
   * @throws IOException when failed to get the external IP address from the metadata server.
   */
  public String getWebSocketURL() throws IOException {
    return "ws://" + getHostname() + ":" + this.getPort() + "/";
  }

Ref

Architecture

Metadata

Metadata

Assignees

Labels

🚨This issue needs some love.triage meI really want to be triaged.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions