From bbc158ec6e028beb4453be974b9008b064af1345 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=A8=E5=8F=B7=E6=95=AC?= <153802103@qq.com> Date: Mon, 6 Jan 2025 11:57:49 +0800 Subject: [PATCH] =?UTF-8?q?=E9=92=93=E6=89=8B=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../script/scene_Main/Thebestfishman.meta | 8 + .../scene_Main/Thebestfishman/WebBeton.cs | 141 +++++++++ .../Thebestfishman/WebBeton.cs.meta | 11 + .../scene_Main/Thebestfishman/WebFishing.cs | 137 +++++++++ .../Thebestfishman/WebFishing.cs.meta | 11 + .../scene_Main/Thebestfishman/WebJoinroom.cs | 270 ++++++++++++++++++ .../Thebestfishman/WebJoinroom.cs.meta | 11 + 7 files changed, 589 insertions(+) create mode 100644 meng_yao/Assets/script/scene_Main/Thebestfishman.meta create mode 100644 meng_yao/Assets/script/scene_Main/Thebestfishman/WebBeton.cs create mode 100644 meng_yao/Assets/script/scene_Main/Thebestfishman/WebBeton.cs.meta create mode 100644 meng_yao/Assets/script/scene_Main/Thebestfishman/WebFishing.cs create mode 100644 meng_yao/Assets/script/scene_Main/Thebestfishman/WebFishing.cs.meta create mode 100644 meng_yao/Assets/script/scene_Main/Thebestfishman/WebJoinroom.cs create mode 100644 meng_yao/Assets/script/scene_Main/Thebestfishman/WebJoinroom.cs.meta diff --git a/meng_yao/Assets/script/scene_Main/Thebestfishman.meta b/meng_yao/Assets/script/scene_Main/Thebestfishman.meta new file mode 100644 index 00000000..4bd07903 --- /dev/null +++ b/meng_yao/Assets/script/scene_Main/Thebestfishman.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: bcbd296c0613aa345925c1068e00107c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/meng_yao/Assets/script/scene_Main/Thebestfishman/WebBeton.cs b/meng_yao/Assets/script/scene_Main/Thebestfishman/WebBeton.cs new file mode 100644 index 00000000..01ef8e0c --- /dev/null +++ b/meng_yao/Assets/script/scene_Main/Thebestfishman/WebBeton.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using System.Net.WebSockets; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using UnityEngine; +using Newtonsoft.Json; +public class WebBeton : MonoBehaviour +{ + private ClientWebSocket _webSocket; + private const string WebSocketUri = "ws://47.95.201.243:9527/api/ws"; + private const string AuthorizationValue = "Bearer VH8XwWuu_iVjEPYQmCq1E2rITTg"; + public int count = 0; + + private async void Start() + { + await ConnectWebSocket(); + + // 准备 JSON 数据 + var message = new + { + code = "FISHING", + content = "{\"action\":\"BETTING\",\"count\":1}" + }; + + // 将对象序列化为 JSON 字符串 + string jsonMessage = JsonUtility.ToJson(message); + + // 调用发送方法 + await SendJsonMessage(count); + } + + private async Task ConnectWebSocket() + { + _webSocket = new ClientWebSocket(); + + // 添加 Authorization 头 + _webSocket.Options.SetRequestHeader("Authorization", AuthorizationValue); + + try + { + Debug.Log("正在连接到 WebSocket..."); + await _webSocket.ConnectAsync(new Uri(WebSocketUri), CancellationToken.None); + Debug.Log("WebSocket 连接成功!"); + + // 开始接收消息 + _ = ReceiveMessages(); + } + catch (Exception e) + { + Debug.LogError($"WebSocket 连接失败:{e.Message}"); + } + } + + private async Task ReceiveMessages() + { + var buffer = new byte[1024]; + + try + { + while (_webSocket.State == WebSocketState.Open) + { + var result = await _webSocket.ReceiveAsync(new ArraySegment(buffer), CancellationToken.None); + + if (result.MessageType == WebSocketMessageType.Close) + { + Debug.Log("WebSocket 连接已被服务器关闭。"); + await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "关闭连接", CancellationToken.None); + } + else + { + var message = Encoding.UTF8.GetString(buffer, 0, result.Count); + Debug.Log($"接收到消息:{message}"); + + + // 解析消息为 Fishresponse 对象 + FishBetonresponse fishResponse = JsonConvert.DeserializeObject(message); + Promptmgr.Instance.PromptBubble(fishResponse.message); + // 检查是否成功反序列化 + if (fishResponse != null && fishResponse.data != null) + { + Debug.Log($"余额: {fishResponse.data.balance}"); + Debug.Log($"价格: {fishResponse.data.price}"); + Debug.Log($"剩余数量: {fishResponse.data.surplus_count}"); + } + else + { + Debug.LogWarning("收到的消息无法解析为 Fishresponse 对象。"); + } + + } + } + } + catch (Exception e) + { + Debug.LogError($"接收消息时出错:{e.Message}"); + } + } + + + public async Task SendJsonMessage(int count) + { + if (_webSocket == null || _webSocket.State != WebSocketState.Open) + { + Debug.LogError("WebSocket 未连接,无法发送消息。"); + return; + } + + try + { + var message = new + { + code = "FISHING", + content = $"{{\"action\":\"BETTING\",\"count\":{count}}}" + }; + + // 将对象序列化为 JSON 字符串 + string jsonMessage = JsonConvert.SerializeObject(message); + var encodedMessage = Encoding.UTF8.GetBytes(jsonMessage); + var buffer = new ArraySegment(encodedMessage); + + await _webSocket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); + Debug.Log($"已发送 JSON 消息:{jsonMessage}"); + } + catch (Exception e) + { + Debug.LogError($"发送消息时出错:{e.Message}"); + } + } + + private async void OnApplicationQuit() + { + if (_webSocket != null && _webSocket.State == WebSocketState.Open) + { + await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "应用程序退出", CancellationToken.None); + _webSocket.Dispose(); + Debug.Log("WebSocket 连接已关闭。"); + } + } +} diff --git a/meng_yao/Assets/script/scene_Main/Thebestfishman/WebBeton.cs.meta b/meng_yao/Assets/script/scene_Main/Thebestfishman/WebBeton.cs.meta new file mode 100644 index 00000000..46b7fd4e --- /dev/null +++ b/meng_yao/Assets/script/scene_Main/Thebestfishman/WebBeton.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1e7c2d58554fa36479761c2cbf8e106b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/meng_yao/Assets/script/scene_Main/Thebestfishman/WebFishing.cs b/meng_yao/Assets/script/scene_Main/Thebestfishman/WebFishing.cs new file mode 100644 index 00000000..07d22115 --- /dev/null +++ b/meng_yao/Assets/script/scene_Main/Thebestfishman/WebFishing.cs @@ -0,0 +1,137 @@ +using System; +using System.Collections.Generic; +using System.Net.WebSockets; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using UnityEngine; +using Newtonsoft.Json; +using System.Drawing; +public class WebFishing : MonoBehaviour +{ + private ClientWebSocket _webSocket; + private const string WebSocketUri = "ws://47.95.201.243:9527/api/ws"; + private const string AuthorizationValue = "Bearer VH8XwWuu_iVjEPYQmCq1E2rITTg"; + + private async void Start() + { + await ConnectWebSocket(); + + // 准备 JSON 数据 + var message = new + { + code = "FISHING", + content = "{\"action\":\"FISHING\"}" + }; + + // 将对象序列化为 JSON 字符串 + string jsonMessage = JsonUtility.ToJson(message); + + // 调用发送方法 + await SendJsonMessage("{ \"code\": \"FISHING\", \"content\": \"{\\\"action\\\":\\\"FISHING\\\"}\" }"); + } + + private async Task ConnectWebSocket() + { + _webSocket = new ClientWebSocket(); + + // 添加 Authorization 头 + _webSocket.Options.SetRequestHeader("Authorization", AuthorizationValue); + + try + { + Debug.Log("正在连接到 WebSocket..."); + await _webSocket.ConnectAsync(new Uri(WebSocketUri), CancellationToken.None); + Debug.Log("WebSocket 连接成功!"); + + // 开始接收消息 + _ = ReceiveMessages(); + } + catch (Exception e) + { + Debug.LogError($"WebSocket 连接失败:{e.Message}"); + } + } + + private async Task ReceiveMessages() + { + var buffer = new byte[1024]; + + try + { + while (_webSocket.State == WebSocketState.Open) + { + var result = await _webSocket.ReceiveAsync(new ArraySegment(buffer), CancellationToken.None); + + if (result.MessageType == WebSocketMessageType.Close) + { + Debug.Log("WebSocket 连接已被服务器关闭。"); + await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "关闭连接", CancellationToken.None); + } + else + { + var message = Encoding.UTF8.GetString(buffer, 0, result.Count); + Debug.Log($"接收到消息:{message}"); + + + // 解析消息为 Fishresponse 对象 + Fishingresponse fishResponse = JsonConvert.DeserializeObject(message); + Promptmgr.Instance.PromptBubble(fishResponse.message); + // 检查是否成功反序列化 + if (fishResponse != null && fishResponse.data != null) + { + Debug.Log($"余额: {fishResponse.data.balance}"); + Debug.Log($"价格: {fishResponse.data.price}"); + Debug.Log($"剩余数量: {fishResponse.data.surplus_count}"); + Debug.Log($"余额: {fishResponse.data.prize.id}"); + Debug.Log($"余额: {fishResponse.data.prize.name}"); + Debug.Log($"余额: {fishResponse.data.prize.type}"); + } + else + { + Debug.LogWarning("收到的消息无法解析为 Fishresponse 对象。"); + } + + } + } + } + catch (Exception e) + { + Debug.LogError($"接收消息时出错:{e.Message}"); + } + } + + + public async Task SendJsonMessage(string json) + { + if (_webSocket == null || _webSocket.State != WebSocketState.Open) + { + Debug.LogError("WebSocket 未连接,无法发送消息。"); + return; + } + + try + { + var encodedMessage = Encoding.UTF8.GetBytes(json); + var buffer = new ArraySegment(encodedMessage); + + await _webSocket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); + Debug.Log($"已发送 JSON 消息:{json}"); + } + catch (Exception e) + { + Debug.LogError($"发送消息时出错:{e.Message}"); + } + } + + private async void OnApplicationQuit() + { + if (_webSocket != null && _webSocket.State == WebSocketState.Open) + { + await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "应用程序退出", CancellationToken.None); + _webSocket.Dispose(); + Debug.Log("WebSocket 连接已关闭。"); + } + } +} + diff --git a/meng_yao/Assets/script/scene_Main/Thebestfishman/WebFishing.cs.meta b/meng_yao/Assets/script/scene_Main/Thebestfishman/WebFishing.cs.meta new file mode 100644 index 00000000..1b6efd30 --- /dev/null +++ b/meng_yao/Assets/script/scene_Main/Thebestfishman/WebFishing.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 29b5ece7ff1f9c946aee00668809f293 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/meng_yao/Assets/script/scene_Main/Thebestfishman/WebJoinroom.cs b/meng_yao/Assets/script/scene_Main/Thebestfishman/WebJoinroom.cs new file mode 100644 index 00000000..7858f547 --- /dev/null +++ b/meng_yao/Assets/script/scene_Main/Thebestfishman/WebJoinroom.cs @@ -0,0 +1,270 @@ +using System; +using System.Collections.Generic; +using System.Net.WebSockets; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using UnityEngine; +using Newtonsoft.Json; +public class WebJoinroom : MonoBehaviour +{ + private ClientWebSocket _webSocket; + private const string WebSocketUri = "ws://47.95.201.243:9527/api/ws"; + private const string AuthorizationValue = "Bearer VH8XwWuu_iVjEPYQmCq1E2rITTg"; + public int count = 0; + + private async void Start() + { + await ConnectWebSocket(); + + // 鍑嗗 JSON 鏁版嵁 + var message = new + { + code = "FISHING", + content = "{\\\"action\\\":\\\"INFO\\\"}" + }; + + // 灏嗗璞″簭鍒楀寲涓 JSON 瀛楃涓 + string jsonMessage = JsonUtility.ToJson(message); + + // 璋冪敤鍙戦佹柟娉 + await SendJsonMessage("{ \"code\": \"FISHING\", \"content\": \"{\\\"action\\\":\\\"INFO\\\"}\" }"); + await SendJsonMessage(count); + await SendJsonMessage("{ \"code\": \"FISHING\", \"content\": \"{\\\"action\\\":\\\"FISHING\\\"}\" }"); + } + + private async Task ConnectWebSocket() + { + _webSocket = new ClientWebSocket(); + + // 娣诲姞 Authorization 澶 + _webSocket.Options.SetRequestHeader("Authorization", AuthorizationValue); + + try + { + Debug.Log("姝e湪杩炴帴鍒 WebSocket..."); + await _webSocket.ConnectAsync(new Uri(WebSocketUri), CancellationToken.None); + Debug.Log("WebSocket 杩炴帴鎴愬姛锛"); + + // 寮濮嬫帴鏀舵秷鎭 + _ = ReceiveMessages(); + } + catch (Exception e) + { + Debug.LogError($"WebSocket 杩炴帴澶辫触锛歿e.Message}"); + } + } + + private async Task ReceiveMessages() + { + var buffer = new byte[1024]; + + try + { + while (_webSocket.State == WebSocketState.Open) + { + var result = await _webSocket.ReceiveAsync(new ArraySegment(buffer), CancellationToken.None); + + if (result.MessageType == WebSocketMessageType.Close) + { + Debug.Log("WebSocket 杩炴帴宸茶鏈嶅姟鍣ㄥ叧闂"); + await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "鍏抽棴杩炴帴", CancellationToken.None); + } + else + { + var message = Encoding.UTF8.GetString(buffer, 0, result.Count); + Debug.Log($"鎺ユ敹鍒版秷鎭細{message}"); + + var baseResponse = JsonConvert.DeserializeObject(message); + + if (baseResponse != null) + { + switch (baseResponse.code) + { + // 瑙f瀽娑堟伅涓 Fishresponse 瀵硅薄 + case "FISHING_INFO": + // 瑙f瀽涓 FishJoinroomresponse 绫诲瀷 + FishJoinroomresponse fishResponse = JsonConvert.DeserializeObject(message); + if (fishResponse?.data != null) + { + Debug.Log($"浣欓: {fishResponse.data.balance}"); + Debug.Log($"浠锋牸: {fishResponse.data.price}"); + Debug.Log($"鍓╀綑鏁伴噺: {fishResponse.data.surplus_count}"); + Debug.Log($"鐜╂硶浠嬬粛: {fishResponse.data.intro_text}"); + foreach (var item in fishResponse.data.items) + { + Debug.Log($"鐗╁搧ID: {item.id}, 鐗╁搧鍚嶇О: {item.name}, 绫诲瀷: {item.type}"); + } + } + break; + + case "FISHING_BETTING": + // 瑙f瀽娑堟伅涓 Fishresponse 瀵硅薄 + FishBetonresponse fishResponse1 = JsonConvert.DeserializeObject(message); + Promptmgr.Instance.PromptBubble(fishResponse1.message); + // 妫鏌ユ槸鍚︽垚鍔熷弽搴忓垪鍖 + if (fishResponse1 != null && fishResponse1.data != null) + { + Debug.Log($"浣欓: {fishResponse1.data.balance}"); + Debug.Log($"浠锋牸: {fishResponse1.data.price}"); + Debug.Log($"鍓╀綑鏁伴噺: {fishResponse1.data.surplus_count}"); + } + else + { + Debug.LogWarning("鏀跺埌鐨勬秷鎭棤娉曡В鏋愪负 Fishresponse 瀵硅薄銆"); + } + break; + case "FISHING_FISHING": + + // 瑙f瀽娑堟伅涓 Fishresponse 瀵硅薄 + Fishingresponse fishResponse2 = JsonConvert.DeserializeObject(message); + Promptmgr.Instance.PromptBubble(fishResponse2.message); + // 妫鏌ユ槸鍚︽垚鍔熷弽搴忓垪鍖 + if (fishResponse2 != null && fishResponse2.data != null) + { + Debug.Log($"浣欓: {fishResponse2.data.balance}"); + Debug.Log($"浠锋牸: {fishResponse2.data.price}"); + Debug.Log($"鍓╀綑鏁伴噺: {fishResponse2.data.surplus_count}"); + Debug.Log($"浣欓: {fishResponse2.data.prize.id}"); + Debug.Log($"浣欓: {fishResponse2.data.prize.name}"); + Debug.Log($"浣欓: {fishResponse2.data.prize.type}"); + } + else + { + Debug.LogWarning("鏀跺埌鐨勬秷鎭棤娉曡В鏋愪负 Fishresponse 瀵硅薄銆"); + } + break; + } + } + + + + } + } + } + catch (Exception e) + { + Debug.LogError($"鎺ユ敹娑堟伅鏃跺嚭閿欙細{e.Message}"); + } + } + + public async Task SendJsonMessage(int count) + { + if (_webSocket == null || _webSocket.State != WebSocketState.Open) + { + Debug.LogError("WebSocket 鏈繛鎺ワ紝鏃犳硶鍙戦佹秷鎭"); + return; + } + + try + { + var message = new + { + code = "FISHING", + content = $"{{\"action\":\"BETTING\",\"count\":{count}}}" + }; + + // 灏嗗璞″簭鍒楀寲涓 JSON 瀛楃涓 + string jsonMessage = JsonConvert.SerializeObject(message); + var encodedMessage = Encoding.UTF8.GetBytes(jsonMessage); + var buffer = new ArraySegment(encodedMessage); + + await _webSocket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); + Debug.Log($"宸插彂閫 JSON 娑堟伅锛歿jsonMessage}"); + } + catch (Exception e) + { + Debug.LogError($"鍙戦佹秷鎭椂鍑洪敊锛歿e.Message}"); + } + } + public async Task SendJsonMessage(string json) + { + if (_webSocket == null || _webSocket.State != WebSocketState.Open) + { + Debug.LogError("WebSocket 鏈繛鎺ワ紝鏃犳硶鍙戦佹秷鎭"); + return; + } + + try + { + var encodedMessage = Encoding.UTF8.GetBytes(json); + var buffer = new ArraySegment(encodedMessage); + + await _webSocket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); + Debug.Log($"宸插彂閫 JSON 娑堟伅锛歿json}"); + } + catch (Exception e) + { + Debug.LogError($"鍙戦佹秷鎭椂鍑洪敊锛歿e.Message}"); + } + } + + private async void OnApplicationQuit() + { + if (_webSocket != null && _webSocket.State == WebSocketState.Open) + { + await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "搴旂敤绋嬪簭閫鍑", CancellationToken.None); + _webSocket.Dispose(); + Debug.Log("WebSocket 杩炴帴宸插叧闂"); + } + } +} +public class BaseResponse +{ + public string code { get; set; } + public string message { get; set; } +} +// 杩斿洖鏁版嵁绫 +public class FishJoinroomresponse +{ + public string code { get; set; } + public string message { get; set; } + public FishJoinroomData data { get; set; } +} + +public class FishJoinroomData +{ + public float balance { get; set; } + public int price { get; set; } + public int surplus_count { get; set; } + public string intro_text { get; set; } + public List items { get; set; } +} + +public class FishJoinroom +{ + public int id { get; set; } + public string name { get; set; } + public int type { get; set; } +} +public class Fishingresponse +{ + public string code { get; set; } + public string message { get; set; } + public FishingData data { get; set; } +} +public class FishingData +{ + public float balance { get; set; } + public int price { get; set; } + public int surplus_count { get; set; } + public Prize prize { get; set; } +} +public class Prize +{ + public int id { get; set; } + public string name { get; set; } + public int type { get; set; } +} +public class FishBetonresponse +{ + public string code { get; set; } + public string message { get; set; } + public FishBetondata data { get; set; } +} +public class FishBetondata +{ + public float balance { get; set; } + public int price { get; set; } + public int surplus_count { get; set; } +} diff --git a/meng_yao/Assets/script/scene_Main/Thebestfishman/WebJoinroom.cs.meta b/meng_yao/Assets/script/scene_Main/Thebestfishman/WebJoinroom.cs.meta new file mode 100644 index 00000000..f977c093 --- /dev/null +++ b/meng_yao/Assets/script/scene_Main/Thebestfishman/WebJoinroom.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ec0bc6b6d3f7fd044847aebc4ea31592 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: