Trying to establish a connection between Angular and Unity has been challenging for me. I can't seem to get them to communicate with each other.
My goal is to have Angular "announce" when someone enters a room, and have Unity "greet" the user entering the room.
Despite not encountering any errors, I still can't make it work. When Unity invokes a method, it works fine, but if Angular does it, Unity doesn't respond.
Below are the relevant code snippets that I'm aware of. Any help in figuring this out would be greatly appreciated.
signalr.service.ts (angular)
hubConnection: signalR.HubConnection;
async StartConnection(): Promise<signalR.HubConnection>
{
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl(environment.hubURL + "Blackjack", {
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets
})
.build();
try
{
await this.hubConnection.start();
console.log("Hub connection started!");
return new Promise<signalR.HubConnection>((resolve) => { resolve(this.hubConnection) });
} catch (err)
{
return new Promise<signalR.HubConnection>((resolve, reject) =>
{ reject(console.error("Error while starting connection" + err)) });
}
}
blackjack.component.ts (angular)
ngOnInit(): void
{
this.signalrService.StartConnection().then((hubConnection) => {
this.signalrService.GetUser().subscribe(user => this.JoinRoom(user));
console.log("ID: " + hubConnection.connectionId);
});
this.signalrService.hubConnection.on("JoinRoomResponse", (user) => this.OnJoinRoom(user));
}
BlackjackHub (server)
public class BlackjackHub : Hub
{
public async Task JoinRoom(User user)
{
await Clients.All.SendAsync("JoinRoomResponse", user);
}
public async Task SendMessage(string author, string message)
{
await Clients.All.SendAsync("UpdateMessage", author, message);
}
}
Program & Startup (server init)
app.UseWebSockets();
app.UseEndpoints(x => {
x.MapControllers();
x.MapHub<BlackjackHub>("Blackjack");
});
Connector.cs (unity)
public class Connector
{
public Action<User> OnConnected;
public Action<string, string> OnMessageRecieved;
public Action OnDeal;
private HubConnection _connection;
public async Task InitAsync()
{
_connection = new HubConnectionBuilder()
.WithUrl("https://localhost:5001/Blackjack", HttpTransportType.WebSockets)
.Build();
_connection.On<User>("JoinRoomResponse", (user) =>
{
OnConnected?.Invoke(new User(user));
});
_connection.On("DealCards", () => OnDeal?.Invoke());
_connection.On<string, string>("SendMessage", (author, message) =>
{
OnMessageRecieved?.Invoke(author, message);
});
await StartConnectionAsync();
}
private async Task StartConnectionAsync()
{
try
{
await _connection.StartAsync();
Debug.Log($"Hub Connection State : {_connection.State} \nConnection ID : {_connection.ConnectionId}");
}
catch (Exception ex)
{
Debug.LogError(ex);
}
}
}
NetworkManager.cs (unity)
public class NetworkManager : MonoBehaviour
{
private static NetworkManager _instance;
public static NetworkManager Instance
{
get { return _instance; }
}
private Connector _connector;
public List<User> users = new List<User>();
private void Awake()
{
if(_instance != null && _instance != this)
{
Destroy(this);
}
else
{
_instance = this;
}
}
private void Start()
{
StartCoroutine(nameof(StartAsync));
}
public async Task StartAsync()
{
_connector = new Connector();
_connector.OnConnected += OnConnected;
_connector.OnMessageRecieved += OnMessageRecieved;
await _connector.InitAsync();
}
public async void OnMessageRecieved(string author, string message)
{
Debug.Log($"{author}: {message}");
await Task.Delay(1);
}
public async void OnConnected (User user)
{
Debug.Log($"{user.Email} just joined.");
users.Add(user);
await Task.Delay(1);
}
}
When tested in Unity, the following output appeared on the console:
https://i.sstatic.net/FcWMV.png
And here is the output from the browser:
https://i.sstatic.net/1GVLE.png
If I disable the WebSocket Transport option in Angular, the ID shows a value:
https://i.sstatic.net/59S99.png