Cysharp / MagicOnion

Unified Realtime/API framework for .NET platform and Unity.
MIT License
3.8k stars 424 forks source link

Cannot work after changing to MemoryPack #741

Open cjhxajh opened 7 months ago

cjhxajh commented 7 months ago

Modifications made based on ChatApp, MessagePack works normally After changing to MemoryPack, the connection to the service failed.

Environment: .Net 8 / Unity2022.3.16 "MagicOnion.Serialization.MemoryPack" Version="6.0.0-preview" "MagicOnion.Server" Version="6.0.0" "MemoryPack" Version="1.10.0"

"MagicOnion.Client" Version="6.0.1" Server Log:

dbug: MagicOnion.Server.MagicOnionEngine[1]
      BeginBuildServiceDefinition
dbug: MagicOnion.Server.MagicOnionEngine[2]
      EndBuildServiceDefinition elapsed:26.8054
trce: Grpc.AspNetCore.Server.Model.Internal.ServiceRouteBuilder[2]
      Discovering gRPC methods for MagicOnion.Server.Glue.MagicOnionGlueService`1[MagicOnionGlue].
dbug: Grpc.AspNetCore.Server.Model.Internal.ServiceRouteBuilder[3]
      No gRPC methods discovered for MagicOnion.Server.Glue.MagicOnionGlueService`1[MagicOnionGlue].
warn: Microsoft.AspNetCore.Server.Kestrel[0]
      Overriding address(es) 'http://localhost:5000, https://localhost:5001, http://localhost:5002'. Binding to endpoints defined via IConfiguration and/or UseKestrel() instead.
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5002
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
      Content root path: F:\SvnLocal_SVN\GrpcTest\GrpcTest.Server\GrpcTest.MagicOnion
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
      Request starting HTTP/2 POST http://localhost:5000/IChatHub/Connect - application/grpc -
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
      Executing endpoint 'gRPC - Unimplemented service'
info: Grpc.AspNetCore.Server.Internal.ServerCallHandlerFactory[1]
      Service 'IChatHub' is unimplemented.
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
      Executed endpoint 'gRPC - Unimplemented service'
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
      Request finished HTTP/2 POST http://localhost:5000/IChatHub/Connect - 200 0 application/grpc 29.8193ms
info: Microsoft.AspNetCore.Server.Kestrel[32]
      Connection id "0HN1O2KUR3T61", Request id "0HN1O2KUR3T61:00000001": the application completed without reading the entire request body.

ClientLog:

[12:46:21]Connecting to the server...
[12:46:21]Grpc.Core.RpcException: Status(StatusCode="Unimplemented", Detail="Service is unimplemented.")
[12:46:26]Connecting to the server...
[12:46:26]Grpc.Core.RpcException: Status(StatusCode="Unimplemented", Detail="Service is unimplemented.")

Server Code:

using MagicOnion.Serialization.MemoryPack;
using Microsoft.AspNetCore.Server.Kestrel.Core;

MagicOnionSerializerProvider.Default = MemoryPackMagicOnionSerializerProvider.Instance;
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(options =>
{
    // WORKAROUND: Accept HTTP/2 only to allow insecure HTTP/2 connections during development.
    options.ConfigureEndpointDefaults(endpointOptions =>
    {
        endpointOptions.Protocols = HttpProtocols.Http2;
    });
});
builder.Services.AddGrpc();
builder.Services.AddMagicOnion();

var app = builder.Build();
app.MapMagicOnionService();
app.Run();

Shared Code: Requests.cs Replace with MemoryPack

using MemoryPack;
namespace GrpcTest.Shared.MessageObjects
{
    /// <summary>
    /// Room participation information
    /// </summary>
    [MemoryPackable]
    public partial struct JoinRequest
    {
        public string RoomName { get; set; }

        public string UserName { get; set; }
    }
}

Responses.cs Replace with MemoryPack

using MemoryPack;
namespace GrpcTest.Shared.MessageObjects
{
    /// <summary>
    /// Message information
    /// </summary>
    [MemoryPackable]
    public partial struct MessageResponse
    {
        public string UserName { get; set; }

        public string Message { get; set; }
    }
}

Client Code for Unity:

[MagicOnionClientGeneration(typeof(GrpcTest.Shared.Services.IChatService), Serializer = GenerateSerializerType.MemoryPack)]
partial class MagicOnionClientInitializer { }

 [RuntimeInitializeOnLoadMethod]
 static void InitSetting()
 {
     StaticCompositeResolver.Instance.Register(              
            //MagicOnionClientInitializer.Resolver,
            //MessagePack.Resolvers.GeneratedResolver.Instance,              
            BuiltinResolver.Instance,
            PrimitiveObjectResolver.Instance
        );
    // MessagePackSerializer.DefaultOptions = MessagePackSerializer.DefaultOptions.WithResolver(StaticCompositeResolver.Instance);

     MagicOnionSerializerProvider.Default = MemoryPackMagicOnionSerializerProvider.Instance;
     //MagicOnionMemoryPackFormatterProvider.RegisterFormatters();

     GrpcChannelProviderHost.Initialize(
             new GrpcNetClientGrpcChannelProvider(() => new GrpcChannelOptions()
             {
                 HttpHandler = new Cysharp.Net.Http.YetAnotherHttpHandler()
                 {
                     Http2Only = true,
                 }
             }));
     // NOTE: If you want to use self-signed certificate for SSL/TLS connection
     //var cred = new SslCredentials(File.ReadAllText(Path.Combine(Application.streamingAssetsPath, "server.crt")));
     //GrpcChannelProviderHost.Initialize(new DefaultGrpcChannelProvider(new GrpcCCoreChannelOptions(channelCredentials: cred)));
 }

private async UniTask InitializeClientAsync()
{
    // Initialize the Hub
    // NOTE: If you want to use SSL/TLS connection, see InitialSettings.OnRuntimeInitialize method.
   this.channel = GrpcChannelx.ForAddress("http://localhost:5000");    
    while (!shutdownCancellation.IsCancellationRequested)
    {
        try
        {
            Debug.Log($"Connecting to the server...");
            this.streamingClient = await StreamingHubClient.ConnectAsync<IChatHub, IChatHubReceiver>(this.channel, this);//, cancellationToken: shutdownCancellation.Token
            this.RegisterDisconnectEvent(streamingClient);
            Debug.Log($"Connection is established.");
            break;
        }
        catch (Exception e)
        {
            Debug.LogError(e);
        }          
        await UniTask.WaitForSeconds(5f);
    }  
    this.client = MagicOnionClient.Create<IChatService>(this.channel);
}
0x5143 commented 5 months ago

Try changing the TargetFramework of ChatApp.Shared.csproj to net8.0

mayuki commented 5 months ago
trce: Grpc.AspNetCore.Server.Model.Internal.ServiceRouteBuilder[2]
      Discovering gRPC methods for MagicOnion.Server.Glue.MagicOnionGlueService`1[MagicOnionGlue].
dbug: Grpc.AspNetCore.Server.Model.Internal.ServiceRouteBuilder[3]
      No gRPC methods discovered for MagicOnion.Server.Glue.MagicOnionGlueService`1[MagicOnionGlue].

The MagicOnion server does not seem to recognize the IChatHub implementation, which inherits from StreamingHubBase?