-
Notifications
You must be signed in to change notification settings - Fork 75
/
SocketIOScript.cs
87 lines (74 loc) · 1.82 KB
/
SocketIOScript.cs
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Quobject.SocketIoClientDotNet.Client;
using Newtonsoft.Json;
public class ChatData {
public string id;
public string msg;
};
public class SocketIOScript : MonoBehaviour {
public string serverURL = "http://localhost:3000";
public InputField uiInput = null;
public Button uiSend = null;
public Text uiChatLog = null;
protected Socket socket = null;
protected List<string> chatLog = new List<string> ();
void Destroy() {
DoClose ();
}
// Use this for initialization
void Start () {
DoOpen ();
uiSend.onClick.AddListener(() => {
SendChat(uiInput.text);
uiInput.text = "";
uiInput.ActivateInputField();
});
}
// Update is called once per frame
void Update () {
lock (chatLog) {
if (chatLog.Count > 0) {
string str = uiChatLog.text;
foreach (var s in chatLog) {
str = str + "\n" + s;
}
uiChatLog.text = str;
chatLog.Clear ();
}
}
}
void DoOpen() {
if (socket == null) {
socket = IO.Socket (serverURL);
socket.On (Socket.EVENT_CONNECT, () => {
lock(chatLog) {
// Access to Unity UI is not allowed in a background thread, so let's put into a shared variable
chatLog.Add("Socket.IO connected.");
}
});
socket.On ("chat", (data) => {
string str = data.ToString();
ChatData chat = JsonConvert.DeserializeObject<ChatData> (str);
string strChatLog = "user#" + chat.id + ": " + chat.msg;
// Access to Unity UI is not allowed in a background thread, so let's put into a shared variable
lock(chatLog) {
chatLog.Add(strChatLog);
}
});
}
}
void DoClose() {
if (socket != null) {
socket.Disconnect ();
socket = null;
}
}
void SendChat(string str) {
if (socket != null) {
socket.Emit ("chat", str);
}
}
}