add 新增远程连接,实现多人游戏
This commit is contained in:
320
Scripts/Lib/RPClient.cs
Normal file
320
Scripts/Lib/RPClient.cs
Normal file
@ -0,0 +1,320 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using Godot;
|
||||
using Godot.Collections;
|
||||
|
||||
namespace RPPackage {
|
||||
public partial class RPClientBaseEDWS : EventDrivenWebSocket {
|
||||
|
||||
public delegate void RPClientEventHandler(string cmd, Dictionary data);
|
||||
public delegate void RPClientErrorHandler(string errCode, string type, string cmd, string errMsg);
|
||||
|
||||
public event RPClientEventHandler OnRPCUser;
|
||||
public event RPClientEventHandler OnRPCRegion;
|
||||
public event RPClientEventHandler OnRPCSession;
|
||||
public event RPClientEventHandler OnRPCMsg;
|
||||
public event RPClientErrorHandler OnRPCError;
|
||||
|
||||
public RPClientBaseEDWS() : base() {
|
||||
OnText += (text) => {
|
||||
GD.Print($"response: {text}");
|
||||
RPMessage msg = RPHelper.HandleIncomingMessage(text);
|
||||
if (msg.Code != "0000") {
|
||||
OnRPCError?.Invoke(msg.Code, msg.Type, msg.Cmd, msg.Data.ToString());
|
||||
return;
|
||||
}
|
||||
switch (msg.Type) {
|
||||
case "user":
|
||||
OnRPCUser?.Invoke(msg.Cmd, msg.Data);
|
||||
break;
|
||||
case "region":
|
||||
OnRPCRegion?.Invoke(msg.Cmd, msg.Data);
|
||||
break;
|
||||
case "session":
|
||||
OnRPCSession?.Invoke(msg.Cmd, msg.Data);
|
||||
break;
|
||||
case "msg":
|
||||
OnRPCMsg?.Invoke(msg.Cmd, msg.Data);
|
||||
break;
|
||||
default:
|
||||
OnRPCError?.Invoke(msg.Code, "unknown", msg.Cmd, msg.Data.ToString());
|
||||
break;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
protected void MakeRPCError(string errCode, string type, string cmd, string errMsg) {
|
||||
this.OnRPCError?.Invoke(errCode, type, cmd, errMsg ?? "null");
|
||||
}
|
||||
}
|
||||
|
||||
public partial class RPClientEDWS : RPClientBaseEDWS {
|
||||
string userName;
|
||||
string userId;
|
||||
string userToken;
|
||||
string regionId;
|
||||
|
||||
public string GetUserId() { return userId; }
|
||||
|
||||
public delegate void SessionRecvHandle(Dictionary msg);
|
||||
public event SessionRecvHandle OnPRCSessionRecv;
|
||||
|
||||
public event RPClientEventHandler OnPRCSessionExit;
|
||||
|
||||
public RPClientEDWS() : base() {
|
||||
OnRPCUser += (cmd, msg) => {
|
||||
switch (cmd) {
|
||||
case "init":
|
||||
userId = msg["userId"].AsString();
|
||||
userToken = msg["token"].AsString();
|
||||
_userInitCallback?.Invoke();
|
||||
break;
|
||||
case "rename":
|
||||
userName = msg["_"].AsString();
|
||||
break;
|
||||
default:
|
||||
MakeRPCError("0000", "user", "unknown", msg?.ToString());
|
||||
break;
|
||||
}
|
||||
};
|
||||
OnRPCRegion += (cmd, msg) => {
|
||||
switch (cmd) {
|
||||
case "add":
|
||||
break;
|
||||
case "inspect":
|
||||
// var regions = msg["_"].AsGodotArray<Dictionary>();
|
||||
_regionRecvCallback?.Invoke(cmd, msg);
|
||||
break;
|
||||
case "list":
|
||||
// var users = msg["_"].AsGodotArray<Dictionary>();
|
||||
_regionRecvCallback?.Invoke(cmd, msg);
|
||||
break;
|
||||
default:
|
||||
MakeRPCError("0000", "region", "unknown", msg?.ToString());
|
||||
break;
|
||||
}
|
||||
};
|
||||
OnRPCSession += (cmd, msg) => {
|
||||
switch (cmd) {
|
||||
case "sendAll":
|
||||
OnPRCSessionRecv?.Invoke(msg);
|
||||
break;
|
||||
case "create":
|
||||
break;
|
||||
case "ackCreate":
|
||||
// GD.PrintErr($"{cmd} {msg} {__SessionAckCreateCallback__ == null}");
|
||||
_sessionAckCreateCallback?.Invoke(cmd, msg);
|
||||
break;
|
||||
case "exit":
|
||||
OnPRCSessionExit?.Invoke(cmd, msg);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
};
|
||||
OnRPCMsg += (cmd, msg) => {
|
||||
switch(cmd) {
|
||||
case "echo":
|
||||
GD.Print(msg["_"].AsString());
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
};
|
||||
OnRPCError += (code, type, cmd, msg) => {
|
||||
};
|
||||
}
|
||||
|
||||
public void ClearRPCClientFunc() {
|
||||
|
||||
}
|
||||
|
||||
public bool IsOnline() {
|
||||
return GetIsConnected() && userId != null;
|
||||
}
|
||||
|
||||
public void ConnectServer(string url) {
|
||||
|
||||
}
|
||||
|
||||
public void ExitServer() {
|
||||
this.SendRPMessage(new RPMessage {
|
||||
Type = "user",
|
||||
Cmd = "exit",
|
||||
Uid = userId,
|
||||
Token = userToken,
|
||||
});
|
||||
userId = null;
|
||||
userToken = null;
|
||||
this.Close();
|
||||
}
|
||||
|
||||
public delegate bool UserInitCallback();
|
||||
private UserInitCallback _userInitCallback;
|
||||
public bool UserInit(string userName, string fingerPrint, UserInitCallback callback) {
|
||||
if (this.GetIsConnected() == false) {
|
||||
return false;
|
||||
}
|
||||
this.SendRPMessage(new RPMessage{
|
||||
Type = "user",
|
||||
Cmd = "init",
|
||||
Data = new Dictionary {
|
||||
{ "userName", userName },
|
||||
{ "fingerPrint", fingerPrint }
|
||||
}
|
||||
});
|
||||
_userInitCallback = null;
|
||||
if (callback != null) _userInitCallback += callback;
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool UserRename(string newName) {
|
||||
if (this.GetIsConnected() == false) {
|
||||
return false;
|
||||
}
|
||||
this.SendRPMessage(new RPMessage{
|
||||
Type = "user",
|
||||
Cmd = "rename",
|
||||
Uid = userId,
|
||||
Token = userToken,
|
||||
Data = new Dictionary {
|
||||
{ "_", newName }
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool RegionAdd(string regionId) {
|
||||
if (this.GetIsConnected() == false || this.userId == null) {
|
||||
return false;
|
||||
}
|
||||
this.SendRPMessage(new RPMessage{
|
||||
Type = "region",
|
||||
Cmd = "add",
|
||||
Uid = userId,
|
||||
Token = userToken,
|
||||
Data = new Dictionary {
|
||||
{ "regionId", regionId }
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
public delegate bool RegionInspectCallback(
|
||||
Array<Dictionary<string, string>> _
|
||||
);
|
||||
private RPClientEventHandler _regionRecvCallback;
|
||||
public bool RegionInspect(string regionId, RegionInspectCallback callback) {
|
||||
if (this.GetIsConnected() == false || this.userId == null) {
|
||||
return false;
|
||||
}
|
||||
_regionRecvCallback = null;
|
||||
_regionRecvCallback += (cmd, msg) => {
|
||||
if (cmd != "inspect") {
|
||||
return;
|
||||
}
|
||||
callback(msg["_"].AsGodotArray<Dictionary<string, string>>());
|
||||
};
|
||||
this.SendRPMessage(new RPMessage{
|
||||
Type = "region",
|
||||
Cmd = "inspect",
|
||||
Uid = userId,
|
||||
Token = userToken,
|
||||
Data = new Dictionary {
|
||||
{ "regionId", regionId }
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
public delegate bool SessionAckCreateCallback(
|
||||
string sessionId,
|
||||
bool res,
|
||||
string reqUserId,
|
||||
string reqUserName
|
||||
);
|
||||
private RPClientEventHandler _sessionAckCreateCallback;
|
||||
public void RegSessionAckCreateCallback(SessionAckCreateCallback recvCallback) {
|
||||
_sessionAckCreateCallback = null;
|
||||
_sessionAckCreateCallback += (cmd, msg) => {
|
||||
string sessionId = msg["sessionId"].AsString();
|
||||
bool res = msg.ContainsKey("res") && msg["res"].AsBool();
|
||||
string reqUserId = msg.ContainsKey("reqUserId") ? msg["reqUserId"].AsString() : null;
|
||||
string reqUserName = msg.ContainsKey("reqUserName") ? msg["reqUserName"].AsString() : null;
|
||||
recvCallback(sessionId, res, reqUserId, reqUserName);
|
||||
};
|
||||
}
|
||||
public bool SessionCreate(string[] usersId) {
|
||||
if (this.GetIsConnected() == false || this.userId == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.SendRPMessage(new RPMessage {
|
||||
Type = "session",
|
||||
Cmd = "create",
|
||||
Uid = userId,
|
||||
Token = userToken,
|
||||
Data = new Dictionary {
|
||||
{ "_", usersId }
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool SessionAckCreate(string sessionId, bool response)
|
||||
{
|
||||
if (this.GetIsConnected() == false || this.userId == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 根据响应情况发送确认消息给服务器
|
||||
string code = response ? "0000" : "0001";
|
||||
this.SendRPMessage(new RPMessage {
|
||||
Type = "session",
|
||||
Cmd = "ackCreate",
|
||||
Uid = userId,
|
||||
Token = userToken,
|
||||
Code = code,
|
||||
Data = new Dictionary {
|
||||
{ "sessionId", sessionId },
|
||||
{ "res", response }
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool SendSessionToAll(string sessionId, Variant data) {
|
||||
if (this.GetIsConnected() == false || this.userId == null || sessionId == null) {
|
||||
return false;
|
||||
}
|
||||
this.SendRPMessage(new RPMessage{
|
||||
Type = "session",
|
||||
Cmd = "sendAll",
|
||||
Uid = userId,
|
||||
Token = userToken,
|
||||
Data = new Dictionary {
|
||||
{ "sessionId", sessionId },
|
||||
{ "msg", data },
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
// ws.OnOpen += (eventName, args) => {
|
||||
// ws.SendRPMessage(new RPMessage{
|
||||
// Type = "user",
|
||||
// Cmd = "tmp",
|
||||
// });
|
||||
// };
|
||||
|
||||
// ws.OnError += (eventName, args) => {
|
||||
// GD.PrintErr(args);
|
||||
// // SetProcess(false);
|
||||
// };
|
||||
|
||||
// ws.OnClose += (eventName, args) => {
|
||||
// // GD.Print("close");
|
||||
// SetProcess(false);
|
||||
// };
|
||||
}
|
||||
}
|
45
Scripts/Lib/RPHelper.cs
Normal file
45
Scripts/Lib/RPHelper.cs
Normal file
@ -0,0 +1,45 @@
|
||||
using Godot;
|
||||
using Godot.Collections;
|
||||
|
||||
namespace RPPackage {
|
||||
public static class RPHelper
|
||||
{
|
||||
public static Dictionary SerializeRPMessage(RPMessage message)
|
||||
{
|
||||
return message.ToDictionary();
|
||||
}
|
||||
|
||||
public static RPMessage DeserializeRPMessage(Dictionary data)
|
||||
{
|
||||
return new RPMessage
|
||||
{
|
||||
Type = data.ContainsKey("type") ? (string)data["type"] : null,
|
||||
Cmd = data.ContainsKey("cmd") ? (string)data["cmd"] : null,
|
||||
Code = data.ContainsKey("code") ? (string)data["code"] : null,
|
||||
Uid = data.ContainsKey("uid") ? (string)data["uid"] : null,
|
||||
Token = data.ContainsKey("token") ? (string)data["token"] : null,
|
||||
Data = data.ContainsKey("data") ? data["data"].AsGodotDictionary() : null,
|
||||
};
|
||||
}
|
||||
|
||||
// 假设你有WebSocket通信的实现,这里仅展示如何使用上述方法
|
||||
public static void SendRPMessage(this EventDrivenWebSocket ws, RPMessage message)
|
||||
{
|
||||
ws.SendJsonEx(RPHelper.SerializeRPMessage(message));
|
||||
}
|
||||
|
||||
public static RPMessage HandleIncomingMessage(string jsonMessage)
|
||||
{
|
||||
var dataDict = Json.ParseString(jsonMessage).AsGodotDictionary();
|
||||
if (dataDict != null)
|
||||
{
|
||||
return RPHelper.DeserializeRPMessage(dataDict);
|
||||
}
|
||||
else
|
||||
{
|
||||
GD.PrintErr("Failed to parse incoming message.");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
33
Scripts/Lib/RPMessage.cs
Normal file
33
Scripts/Lib/RPMessage.cs
Normal file
@ -0,0 +1,33 @@
|
||||
using Godot;
|
||||
using Godot.Collections;
|
||||
|
||||
namespace RPPackage {
|
||||
public class RPMessage
|
||||
{
|
||||
public string Type { get; set; }
|
||||
public string Cmd { get; set; }
|
||||
public Dictionary Data { get; set; }
|
||||
|
||||
public string Uid { get; set; }
|
||||
public string Token { get; set; }
|
||||
public string Code { get; set; }
|
||||
public Dictionary ToDictionary()
|
||||
{
|
||||
var dict = new Dictionary();
|
||||
if (Type != null)
|
||||
dict.Add("type", Type);
|
||||
if (Cmd != null)
|
||||
dict.Add("cmd", Cmd);
|
||||
if (Data != null)
|
||||
dict.Add("data", Data);
|
||||
|
||||
if (Uid != null)
|
||||
dict.Add("uid", Uid);
|
||||
if (Token != null)
|
||||
dict.Add("token", Token);
|
||||
if (Code != null)
|
||||
dict.Add("code", Code);
|
||||
return dict;
|
||||
}
|
||||
}
|
||||
}
|
0
Scripts/Lib/csws.cs
Normal file
0
Scripts/Lib/csws.cs
Normal file
114
Scripts/Lib/gdws.cs
Normal file
114
Scripts/Lib/gdws.cs
Normal file
@ -0,0 +1,114 @@
|
||||
using Godot;
|
||||
using Godot.Collections;
|
||||
|
||||
public partial class EventDrivenWebSocket : WebSocketPeer {
|
||||
public delegate void WebSocketEventHandler(string eventName, params object[] args);
|
||||
public delegate void WSBinMsgEventHandler(byte[] args);
|
||||
public delegate void WSMsgEventHandler(string args);
|
||||
|
||||
public event WebSocketEventHandler OnOpen;
|
||||
public event WSBinMsgEventHandler OnMessage;
|
||||
public event WSMsgEventHandler OnText;
|
||||
public event WSBinMsgEventHandler OnBinary;
|
||||
public event WebSocketEventHandler OnClose;
|
||||
public event WebSocketEventHandler OnError;
|
||||
|
||||
private bool isConnected = false;
|
||||
private bool isCloseEventFired = false;
|
||||
private double connectingTime = double.NegativeInfinity;
|
||||
|
||||
|
||||
public EventDrivenWebSocket() : base() {
|
||||
isConnected = false;
|
||||
}
|
||||
|
||||
public bool GetIsConnected() {
|
||||
return isConnected;
|
||||
}
|
||||
|
||||
public void PollEx(double delta) {
|
||||
base.Poll();
|
||||
CheckAndDispatchEvents(delta);
|
||||
}
|
||||
|
||||
public void ConnectToUrlEx(string url, double delayTime = 3,
|
||||
TlsOptions tlsClientOptions = null) {
|
||||
if (connectingTime >= 0) {
|
||||
return;
|
||||
}
|
||||
Error err = ConnectToUrl(url, tlsClientOptions);
|
||||
if (err != Error.Ok) {
|
||||
OnError?.Invoke("error", err);
|
||||
}
|
||||
connectingTime = delayTime;
|
||||
}
|
||||
|
||||
protected void CheckAndDispatchEvents(double delta) {
|
||||
var state = GetReadyState();
|
||||
switch (state) {
|
||||
case State.Open when !isConnected:
|
||||
isConnected = true;
|
||||
OnOpen?.Invoke("open", null);
|
||||
break;
|
||||
case State.Open:
|
||||
while (GetAvailablePacketCount() > 0) {
|
||||
byte[] packet = GetPacket();
|
||||
OnMessage?.Invoke(packet);
|
||||
if (WasStringPacket()) {
|
||||
OnText?.Invoke(packet.GetStringFromUtf8());
|
||||
} else {
|
||||
OnBinary?.Invoke(packet);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case State.Closed:
|
||||
connectingTime = double.NegativeInfinity;
|
||||
OnClose?.Invoke("closed", GetCloseCode(), GetCloseReason());
|
||||
isConnected = false;
|
||||
break;
|
||||
case State.Closing:
|
||||
// OnClose?.Invoke("closing");
|
||||
break;
|
||||
case State.Connecting:
|
||||
if (connectingTime >= 0) {
|
||||
connectingTime -= delta;
|
||||
} else if (connectingTime != double.NegativeInfinity){
|
||||
connectingTime = double.NegativeInfinity;
|
||||
Close();
|
||||
OnError?.Invoke("connectTimeOut", Error.Timeout);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
// 可以在这里处理其他状态或错误
|
||||
OnError?.Invoke("error", "Unknown WebSocket state.");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void SendBinaryEx(byte[] data) {
|
||||
SendEx(data);
|
||||
}
|
||||
|
||||
public void SendJsonEx(Dictionary msg) {
|
||||
SendTextEx(Json.Stringify(msg));
|
||||
}
|
||||
|
||||
public Error SendTextEx(string message) {
|
||||
if (isConnected) {
|
||||
return SendText(message);
|
||||
} else {
|
||||
OnError?.Invoke("error", "Attempt to send on a closed connection.");
|
||||
return Error.ConnectionError;
|
||||
}
|
||||
}
|
||||
|
||||
public Error SendEx(byte[] message, WriteMode writeMode = WriteMode.Binary) {
|
||||
if (isConnected) {
|
||||
return Send(message, writeMode);
|
||||
} else {
|
||||
OnError?.Invoke("error", "Attempt to send on a closed connection.");
|
||||
return Error.ConnectionError;
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user