using System;
using System.Text;
using NATS.Client;
using NATS.Net;
using System.Threading.Tasks;
using NATS.Client.Core;
using UnityEngine;
using UnityEngine.UI;
public class NatSample : MonoBehaviour
{
private NatsClient client;
//private const string NATS_URL = "nats://localhost:4222"; // NATS 서버 주소
private const string NATS_URL = "ws://localhost:8282"; // NATS 서버 주소
private const string SUBJECT = "test"; // 채팅 채널
async void Start()
{
await ConnectToNats();
}
async Task ConnectToNats()
{
try
{
client = new NatsClient(new NatsOpts { Url = NATS_URL });
await foreach (var msg in client.SubscribeAsync<string>(SUBJECT))
{
Debug.Log($"Received: {msg}");
UpdateChatDisplay(msg.Data);
}
}
catch (Exception e)
{
Debug.LogError($"NATS Connection Error: {e.Message}");
}
}
float t = 0.0f;
private void Update()
{
t += Time.deltaTime;
if (t>3)
{
t = 0;
SendMessage2();
}
}
public async void SendMessage2()
{
if (client == null ) return;
await client.PublishAsync(SUBJECT, "1a2a");
}
void UpdateChatDisplay(string message)
{
Debug.Log("msg:"+ message);
}
async void OnApplicationQuit()
{
if (client != null)
{
await client.DisposeAsync();
}
}
}