首页 > 解决方案 > gRPC 可以集成到 Flutter-web 中吗?

问题描述

我试图融入gPRCflutter-web但总是失败。不知道是我的代码有问题还是GRPC无法集成到flutter-web中。

dependencies:
  flutter:
    sdk: flutter
  grpc: ^2.1.3
  protobuf: ^1.0.1

在此处输入图像描述

这是我的服务器端代码: 在此处输入图像描述

我有两个问题。第一个是是否GRPC可以集成到fluter-web.? 第二个是我需要什么库,有没有例子?谢谢你。

标签: goflutterdartgrpcflutter-web

解决方案


简短的回答,是的,你可以


目前,grpc-web 需要在 gRPC 服务器前面有一个 Web 代理,以将请求和响应转换为浏览器可以使用的东西。有关详细信息,请参阅https://grpc.io/blog/state-of-grpc-web/

您可以使用Envoy作为 Web 代理。

这里使用 envoy 的步骤:

  1. 将您的 Web 客户端频道设置为颤动

    GrpcWebClientChannel.xhr(Uri.parse('http://localhost:8080'));
    
  2. 将服务器设置为侦听以下示例:

    path := "127.0.0.1:3001"
    
  3. 从https://www.envoyproxy.io/安装特使

  4. 为特使创建配置,如下例所示。另存为envoy.yaml

admin:
  access_log_path: /tmp/admin_access.log
  address:
    socket_address: { address: 0.0.0.0, port_value: 9901 }

static_resources:
  listeners:
  - name: listener_0
    address:
      socket_address: { address: 0.0.0.0, port_value: 8080 }
    filter_chains:
    - filters:
      - name: envoy.filters.network.http_connection_manager
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
          codec_type: auto
          stat_prefix: ingress_http
          route_config:
            name: local_route
            virtual_hosts:
            - name: local_service
              domains: ["*"]
              routes:
              - match: { prefix: "/" }
                route:
                  cluster: greeter_service
                  max_stream_duration:
                    grpc_timeout_header_max: 0s
              cors:
                allow_origin_string_match:
                - prefix: "*"
                allow_methods: GET, PUT, DELETE, POST, OPTIONS
                allow_headers: keep-alive,user-agent,cache-control,content-type,content-transfer-encoding,x-accept-content-transfer-encoding,x-accept-response-streaming,x-user-agent,x-grpc-web,grpc-timeout
                max_age: "1728000"
                expose_headers: id,token,grpc-status,grpc-message
          http_filters:
          - name: envoy.filters.http.grpc_web
          - name: envoy.filters.http.cors
          - name: envoy.filters.http.router
  clusters:
  - name: greeter_service
    connect_timeout: 0.25s
    type: logical_dns
    http2_protocol_options: {}
    lb_policy: round_robin
    # win/mac hosts: Use address: host.docker.internal instead of address: localhost in the line below
    load_assignment:
      cluster_name: cluster_0
      endpoints:
        - lb_endpoints:
            - endpoint:
                address:
                  socket_address:
                    address: 0.0.0.0
                    port_value: 3001

  1. 使用配置运行 envoy(Linux 框中的示例):

    $ envoy -c envoy.yaml
    

现在,尝试运行 Flutter Web 客户端和服务器。

请参阅https://github.com/sigurdm/grpc_web_flutter_examplehttps://github.com/grpc/grpc-web/tree/master/net/grpc/gateway/examples/helloworld


推荐阅读