using System;
using System.Text;
using NATS.Client;
using NATS.Net;
using Systehttp://m.Threading.Tasks;
using NATS.Client.Core;
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
public class NatSample : MonoBehaviour
{
private NatsClient client;
private const string NATS_URL = "ws://35.208.138.76:8282"; // NATS 서버 주소
private Dictionary<string, IAsyncSubscription<string>> subscriptions = new Dictionary<string, IAsyncSubscription<string>>();
async void Start()
{
await ConnectToNats();
}
async Task ConnectToNats()
{
try
{
client = new NatsClient(new NatsOpts { Url = NATS_URL });
Debug.Log("Connected to NATS server");
}
catch (Exception e)
{
Debug.LogError($"NATS Connection Error: {e.Message}");
}
}
public async Task AddSubject(string subject)
{
if (client == null || subscriptions.ContainsKey(subject))
return;
try
{
var subscription = client.SubscribeAsync<string>(subject);
subscriptions[subject] = subscription;
_ = Task.Run(async () =>
{
await foreach (var msg in subscription)
{
Debug.Log($"Received on {subject}: {msg.Data}");
UpdateChatDisplay($"{subject}: {msg.Data}");
}
});
Debug.Log($"Added subscription to subject: {subject}");
}
catch (Exception e)
{
Debug.LogError($"Error adding subject {subject}: {e.Message}");
}
}
public async Task RemoveSubject(string subject)
{
if (client == null || !subscriptions.ContainsKey(subject))
return;
try
{
await subscriptions[subject].DisposeAsync();
subscriptions.Remove(subject);
Debug.Log($"Removed subscription from subject: {subject}");
}
catch (Exception e)
{
Debug.LogError($"Error removing subject {subject}: {e.Message}");
}
}
public async Task SendMessage(string subject, string message)
{
if (client == null) return;
try
{
await client.PublishAsync(subject, message);
Debug.Log($"Sent to {subject}: {message}");
}
catch (Exception e)
{
Debug.LogError($"Error sending message: {e.Message}");
}
}
void UpdateChatDisplay(string message)
{
Debug.Log("msg:" + message);
}
async void OnApplicationQuit()
{
if (client != null)
{
foreach (var subscription in subscriptions.Values)
{
await subscription.DisposeAsync();
}
await client.DisposeAsync();
}
}
}