-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnityNeonChatClient.cs
More file actions
94 lines (77 loc) · 2.53 KB
/
UnityNeonChatClient.cs
File metadata and controls
94 lines (77 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using System;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using UnityEngine;
public class UnityNeonChatClient : MonoBehaviour
{
/// <summary>
/// The client's username.
/// </summary>
public string clientUserName;
/// <summary>
/// The message text to be set from your chat UI.
/// </summary>
public string messageText;
/// <summary>
/// The buffer for indirect communication between the main thread and the native plugin.
/// </summary>
private static string _buffer;
/// <summary>
/// Used to update the buffer in the main thread.
/// </summary>
private static bool update;
/// <summary>
/// Assign your own action to this delegate to receive messages from the server.
/// </summary>
public static Action<string> onMessageReceivedAction;
private void Update()
{
if (!update || string.IsNullOrEmpty(_buffer)) return;
update = false;
onMessageReceivedAction?.Invoke(_buffer);
}
delegate void OnNewMessageReceived(string userName, string chatMessage);
[DllImport("NeonChat")]
public static extern void ConnectToNeonChat();
[DllImport("NeonChat")]
public static extern void DisconnectFromNeonChat();
[DllImport("NeonChat")]
public static extern void SendNeonChat(string userName, string chatMessage);
[DllImport("NeonChat")]
static extern void RegisterOnNewMessageReceivedCallback(OnNewMessageReceived callback);
static void OnMessageReceived(string userName, string chatMessage)
{
_buffer += $"\n[{userName}]: {chatMessage}";
update = true;
}
/// <summary>
/// Call send message to send the current message to the server. Usually set through a UI button, or called by a key press.
/// </summary>
public void SendMsg()
{
try
{
SendNeonChat(clientUserName, messageText);
}
catch (Exception e)
{
Debug.Log("Error sending message: " + e.Message);
}
}
public void OnEnable()
{
Debug.Log("Connecting to NeonChat...");
Task.Run(() =>
{
ConnectToNeonChat();
RegisterOnNewMessageReceivedCallback(OnMessageReceived);
onMessageReceivedAction += Debug.Log;
}).ConfigureAwait(false);
}
public void OnDisable()
{
Debug.Log("Disconnecting from NeonChat...");
onMessageReceivedAction -= Debug.Log;
Task.Run(DisconnectFromNeonChat);
}
}