-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUnityWebSocketDemo.cs
79 lines (70 loc) · 2.39 KB
/
UnityWebSocketDemo.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
using Pomelo.UnityWebSocketPomelo;
using SimpleJson;
using System;
using UnityEngine;
namespace UnityWebSocket.Demo
{
public class UnityWebSocketDemo : MonoBehaviour
{
/// <summary>
/// pomelo webgl 客户端
/// </summary>
public UnityWebSocketPomeloClient wpClient = null;
private void Start()
{
if (wpClient == null)
{
wpClient = new UnityWebSocketPomeloClient();
//监听网络状态变化事件
wpClient.NetWorkStateChangedEvent += (state) =>
{
Debug.Log("CurrentState is:" + state);
};
wpClient.initClient("ws://127.0.0.1:34590/", () =>
{
//test 握手并登录
JsonObject msg = new JsonObject();
wpClient.connect(msg, (JsonObject json) =>
{
JsonObject userMessage = new JsonObject();
userMessage["nickname"] = "123456";
wpClient.request("room.room.login", userMessage, OnQuery);
});
});
}
}
void OnQuery(JsonObject result)
{
if (Convert.ToInt32(result["code"]) == 200)
{
wpClient.disconnect();
string host = (string)result["host"];
int port = Convert.ToInt32(result["port"]);
wpClient = new UnityWebSocketPomeloClient();
wpClient.initClient("ws://" + host + ":" + port.ToString() + "/", () =>
{
JsonObject msg = new JsonObject();
wpClient.connect(msg, (JsonObject json) =>
{
JsonObject userMessage = new JsonObject();
userMessage["username"] = "123456";
if (wpClient != null)
{
wpClient.request("room.room.login", userMessage, OnEntry);
}
});
});
}
}
void OnEntry(JsonObject data)
{
//users = data;
//isLoad = true;
}
private void OnApplicationQuit()
{
Debug.Log("OnApplicationQuit");
wpClient.Dispose();
}
}
}