├── BaseService
├── _shard_start.bat
├── _shard_stop.bat
├── common.cfg
├── frontend_service.cfg
├── frontend_service.exe
├── msg.xml
├── msvcp110.dll
├── msvcr110.dll
├── naming_service.cfg
├── naming_service.exe
├── script
│ ├── BaseService.luaprj
│ ├── DataTable
│ │ ├── ProtoMsg.pb
│ │ ├── RoomConfig.json
│ │ └── proto
│ │ │ ├── define_attrib.proto
│ │ │ ├── define_pro.proto
│ │ │ ├── msg_client.proto
│ │ │ ├── msg_doudizhu.proto
│ │ │ └── msg_service.proto
│ ├── Framework
│ │ ├── CJsonUtil.lua
│ │ ├── Class.lua
│ │ ├── Event
│ │ │ ├── EventController.lua
│ │ │ ├── EventRegister.lua
│ │ │ └── EventTrigger.lua
│ │ ├── InitFramework.lua
│ │ ├── List.lua
│ │ ├── Map.lua
│ │ ├── MapMap.lua
│ │ ├── MiddleClass.lua
│ │ ├── Net
│ │ │ ├── BaseService.lua
│ │ │ ├── CallbackServer.lua
│ │ │ ├── NetWorkHandler.lua
│ │ │ ├── TcpCbServer.lua
│ │ │ ├── WebSocketCbServer.lua
│ │ │ └── protobuf.lua
│ │ ├── Queue.lua
│ │ ├── SimpleStateMachine.lua
│ │ ├── Stack.lua
│ │ ├── StateFul.lua
│ │ ├── Test
│ │ │ ├── FSMClass.lua
│ │ │ ├── TestFSM.lua
│ │ │ └── TimerTest.lua
│ │ ├── TimerMgr.lua
│ │ ├── Utils.lua
│ │ └── functions.lua
│ ├── SharedLib
│ │ ├── Event
│ │ │ └── EventType.lua
│ │ ├── InitSharedLib.lua
│ │ └── StaticTableMgr.lua
│ ├── _FES.luaprj
│ └── _FES
│ │ ├── Client
│ │ ├── Client.lua
│ │ └── ClientMgr.lua
│ │ ├── FrontEndService.lua
│ │ ├── Msg
│ │ └── MsgLogin.lua
│ │ ├── Player
│ │ ├── PlayerInfo.lua
│ │ └── PlayerInfoMgr.lua
│ │ └── _FESMain.lua
└── vccorlib110.dll
├── EgretWebSocket
├── .wing
│ ├── launch.json
│ ├── settings.json
│ └── tasks.json
├── bin-debug
│ ├── LoadingUI.js
│ ├── LoadingUI.js.map
│ ├── Main.js
│ ├── Main.js.map
│ ├── Platform.js
│ ├── Platform.js.map
│ ├── module
│ │ ├── ClientModule.js
│ │ ├── ClientModule.js.map
│ │ ├── Json
│ │ │ ├── JsonUser.js
│ │ │ └── JsonUser.js.map
│ │ ├── LoginModule.js
│ │ ├── LoginModule.js.map
│ │ └── Player
│ │ │ ├── PlayerDataModule.js
│ │ │ └── PlayerDataModule.js.map
│ └── network
│ │ ├── Message.js
│ │ ├── Message.js.map
│ │ ├── NetEvent.js
│ │ ├── NetEvent.js.map
│ │ ├── NetMgr.js
│ │ └── NetMgr.js.map
├── egretProperties.json
├── favicon.ico
├── index.html
├── libs
│ └── modules
│ │ ├── assetsmanager
│ │ ├── assetsmanager.d.ts
│ │ ├── assetsmanager.js
│ │ └── assetsmanager.min.js
│ │ ├── egret
│ │ ├── egret.d.ts
│ │ ├── egret.js
│ │ ├── egret.min.js
│ │ ├── egret.web.js
│ │ └── egret.web.min.js
│ │ ├── game
│ │ ├── game.d.ts
│ │ ├── game.js
│ │ └── game.min.js
│ │ ├── promise
│ │ ├── promise.js
│ │ └── promise.min.js
│ │ ├── protobuf-lib
│ │ ├── protobuf-library.d.ts
│ │ ├── protobuf-library.js
│ │ └── protobuf-library.min.js
│ │ ├── protobuf-msg
│ │ ├── protobuf-bundles.d.ts
│ │ ├── protobuf-bundles.js
│ │ └── protobuf-bundles.min.js
│ │ ├── socket
│ │ ├── socket.d.ts
│ │ ├── socket.js
│ │ └── socket.min.js
│ │ └── tween
│ │ ├── tween.d.ts
│ │ ├── tween.js
│ │ └── tween.min.js
├── manifest.json
├── resource
│ ├── assets
│ │ ├── bg.jpg
│ │ └── egret_icon.png
│ ├── config
│ │ └── description.json
│ └── default.res.json
├── scripts
│ ├── api.d.ts
│ ├── bricks
│ │ └── bricks.ts
│ ├── config.android.ts
│ ├── config.bricks.ts
│ ├── config.ios.ts
│ ├── config.ts
│ ├── config.wxgame.ts
│ ├── myplugin.ts
│ ├── node.d.ts
│ ├── tsconfig.json
│ └── wxgame
│ │ └── wxgame.ts
├── src
│ ├── LoadingUI.ts
│ ├── Main.ts
│ ├── Platform.ts
│ ├── module
│ │ ├── ClientModule.ts
│ │ ├── Json
│ │ │ └── JsonUser.ts
│ │ ├── LoginModule.ts
│ │ └── Player
│ │ │ └── PlayerDataModule.ts
│ └── network
│ │ ├── Message.ts
│ │ ├── NetEvent.ts
│ │ └── NetMgr.ts
├── template
│ ├── runtime
│ │ ├── native_loader.js
│ │ ├── native_require.js
│ │ └── runtime_loader.js
│ └── web
│ │ └── index.html
├── tsconfig.json
└── wingProperties.json
├── ExternalLibs
├── ProtobufLib
│ ├── protobuf-library.d.ts
│ ├── protobuf-library.js
│ └── protobuf-library.min.js
└── ProtobufMsg
│ ├── protobuf-bundles.d.ts
│ ├── protobuf-bundles.js
│ └── protobuf-bundles.min.js
├── LICENSE
└── README.md
/BaseService/_shard_start.bat:
--------------------------------------------------------------------------------
1 | @echo off
2 |
3 | REM This script will start all the services with good parameters
4 |
5 | call _shard_stop.bat
6 |
7 | REM set MODE=Debug
8 | REM set MODE=.
9 | set MODE=.
10 |
11 | rem ns
12 | start %MODE%\naming_service --nolog
13 | ping -n 2 127.0.0.1 > NUL 2>&1
14 |
15 | rem pls
16 | rem start %MODE%\player_logic_service --nolog
17 | rem ping -n 2 127.0.0.1 > NUL 2>&1
18 |
19 | rem fes
20 | start %MODE%\frontend_service --nolog
21 | ping -n 2 127.0.0.1 > NUL 2>&1
22 |
23 |
--------------------------------------------------------------------------------
/BaseService/_shard_stop.bat:
--------------------------------------------------------------------------------
1 | @echo off
2 |
3 | REM This script will kill all the services launched by shard_start.bat
4 |
5 | rem ns
6 | taskkill /IM naming_service.exe /F
7 |
8 | rem fes
9 | taskkill /IM frontend_service.exe /F
10 |
11 | rem pls
12 | rem taskkill /IM player_logic_service.exe /F
13 |
14 |
15 |
--------------------------------------------------------------------------------
/BaseService/common.cfg:
--------------------------------------------------------------------------------
1 | // ---- config local variables
2 |
3 | // Used by ConfigFile in EGS and WS
4 | ShardId = 302;
5 |
6 | UpdateTimeout = 20;
7 |
8 | // Used to connect to AES (this file) and to set up AES service (admin_executor_service.cfg)
9 | AESPort="46702";
10 | AESHost="localhost";
11 |
12 | // ---- service NeL variables (used by ConfigFile class)
13 |
14 | WindowStyle = "WIN";
15 |
16 | // don't connect to the old NeLNS AES
17 | DontUseAES = 1;
18 |
19 | // Configure module gateway for layer 5 module comm
20 | /*
21 | StartCommands +=
22 | {
23 | // Create a gateway module
24 | "moduleManager.createModule StandardGateway gw",
25 | // add a layer 5 transport
26 | "gw.transportAdd L5Transport l5",
27 | // open the transport
28 | "gw.transportCmd l5(open)",
29 |
30 | /// Create default connection with admin executor service
31 | // Create a gateway module
32 | "moduleManager.createModule StandardGateway gw_aes",
33 | // create the admin executor service module
34 | "moduleManager.createModule AdminExecutorServiceClient aes_client",
35 | "aes_client.plug gw_aes",
36 |
37 | // create a layer 3 client to connect to aes gateway
38 | "gw_aes.transportAdd L3Client aes_l3c",
39 | "gw_aes.transportCmd aes_l3c(connect addr="+AESHost+":"+AESPort+")",
40 | };
41 | */
42 |
43 | // by default, use localhost to find the naming service
44 | NSHost = "localhost:49901";
45 | NSPort = 49901;
46 |
47 | // A list of vars to graph for any service
48 | GraphVars +=
49 | {
50 | "ProcessUsedMemory", "60000", // every minute
51 | };
52 |
53 | IgnoredFiles = { "continent.cfg", "__read_me.txt", "bandit.html", "flora_primr.primitive" };
54 |
55 | // Set a mainland SessionId.
56 | // Live: Must be 0 for ring shards, non-zero (usually ShardId) for mainland shards
57 | // Dev: Can be non-zero to initially connect a client to a ring shard
58 | NoWSShardId = ShardId;
59 |
60 | // ---- service NeL variables (used by CVariable class)
61 |
62 | // Disable generation / display of nldebug messages
63 | DisableNLDebug = 0;
64 |
65 | // Disable nel net verbose logging
66 | VerboseNETTC = 1;
67 | VerboseLNETL0 = 1;
68 | VerboseLNETL1 = 1;
69 | VerboseLNETL2 = 1;
70 | VerboseLNETL3 = 1;
71 | VerboseLNETL4 = 1;
72 | VerboseLNETL5 = 1;
73 | VerboseLNETL6 = 1;
74 |
75 | // If the update loop is too slow, a thread will produce an assertion.
76 | // By default, the value is set to 10 minutes.
77 | // Set to 0 for no assertion.
78 | UpdateAssertionThreadTimeout = 6000000;
79 |
80 | // how to sleep between 2 network updates
81 | // 0 = pipe
82 | // 1 = usleep
83 | // 2 = nanosleep
84 | // 3 = sched_yield
85 | // 4 = nothing
86 | UseYieldMethod = 0;
87 |
88 | DefaultMaxExpectedBlockSize = 200000000; // 200 M !
89 | DefaultMaxSentBlockSize = 200000000; // 200 M !
90 |
91 | // Will SaveFilesDirectory will be converted to a full path?
92 | ConvertSaveFilesDirectoryToFullPath = 1;
93 |
94 | // Where to save specific shard data (ie: player backup), relatively to SaveShardRoot
95 | SaveFilesDirectory = "";
96 |
97 | // where to save generic shard data (ie: packed_sheet)
98 | WriteFilesDirectory = "data_shard";
99 |
100 | // ---- service custom variables (used by ConfigFile class)
101 |
102 | NegFiltersDebug += { "NETL", "NET" };
103 | NegFiltersInfo += { "NETL" };
104 | NegFiltersWarning += { };
105 |
106 | // where to send error reports
107 | DefaultEmailSMTP = "smtp";
108 | DefaultEmailFrom = "sanguo@0xcc.com";
109 | DefaultEmailTo = "li9chuan@qq.com";
110 |
111 | LogDirectory = "./log/";
112 |
113 | Language = "cn";
114 |
115 |
116 |
--------------------------------------------------------------------------------
/BaseService/frontend_service.cfg:
--------------------------------------------------------------------------------
1 | RootConfigFilename = "common.cfg";
2 |
3 | AESAliasName = "fes_0";
4 | SId = 66;
5 |
6 | NegFiltersDebug = { "NET" };
7 |
8 | GraphVars +=
9 | {
10 | "FPSProcessMsg", "60000", // every minute
11 | };
12 |
13 | StartLuaScript = "_FESMain.lua";
14 |
15 | Paths =
16 | {
17 | "./script/_FES/", // for lua root script
18 | };
19 |
20 | DisplayedVariables += { "", "@LoadLua|loadlua", "@LoadMsg|loadmsg" };
21 |
22 |
23 | MsgCount = true;
24 | SaveEvent = false;
25 |
26 |
--------------------------------------------------------------------------------
/BaseService/frontend_service.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li9chuan/EgretWebSocket/d72c82d6c26d77851c705444e7c9f0143fc249d8/BaseService/frontend_service.exe
--------------------------------------------------------------------------------
/BaseService/msg.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
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 |
--------------------------------------------------------------------------------
/BaseService/msvcp110.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li9chuan/EgretWebSocket/d72c82d6c26d77851c705444e7c9f0143fc249d8/BaseService/msvcp110.dll
--------------------------------------------------------------------------------
/BaseService/msvcr110.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li9chuan/EgretWebSocket/d72c82d6c26d77851c705444e7c9f0143fc249d8/BaseService/msvcr110.dll
--------------------------------------------------------------------------------
/BaseService/naming_service.cfg:
--------------------------------------------------------------------------------
1 | // link the common configuration file
2 | #include "common.cfg"
3 |
4 | DisplayedVariables += { "", "@Services|nsServices" };
5 |
6 | SId = 69;
7 |
8 | DontUseNS = 1;
9 | AESAliasName = "rns";
10 |
11 | NegFiltersDebug = { "NETL" };
12 | NegFiltersInfo = { "NETL" };
13 |
14 | UniqueOnShardServices = {};
15 | UniqueByMachineServices = {};
16 |
17 |
--------------------------------------------------------------------------------
/BaseService/naming_service.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li9chuan/EgretWebSocket/d72c82d6c26d77851c705444e7c9f0143fc249d8/BaseService/naming_service.exe
--------------------------------------------------------------------------------
/BaseService/script/BaseService.luaprj:
--------------------------------------------------------------------------------
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 |
--------------------------------------------------------------------------------
/BaseService/script/DataTable/ProtoMsg.pb:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li9chuan/EgretWebSocket/d72c82d6c26d77851c705444e7c9f0143fc249d8/BaseService/script/DataTable/ProtoMsg.pb
--------------------------------------------------------------------------------
/BaseService/script/DataTable/RoomConfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "RM_DDZ": {
3 | "room_type": "RM_DDZ",
4 | "game_type": "GM_DDZ",
5 | "app_name": "APP_DDZ",
6 | "min_ver": 1.16,
7 | "match": "private",
8 | "room_name": "斗地主",
9 | "enter_level": 0,
10 | "enter_score": 0,
11 | "room_max": 3,
12 | "room_min": 3,
13 | "viewer_max": 5,
14 | "is_goback": 1,
15 | "auto_return": 1,
16 | "room_time": 28800,
17 | "room_icon": "icon_yule",
18 | "room_bg": "Texture/BackGround/nj_mahjong_room_logo_4",
19 | "game_icon": "Texture/BackGround/hall_game_icon_4",
20 | "game_bg": "Texture/BackGround/hall_game_bg",
21 | "enter_game_scene": "BlackJackScene",
22 | "enter_room_scene": "jiuguan"
23 | }
24 | }
--------------------------------------------------------------------------------
/BaseService/script/DataTable/proto/define_attrib.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto2";
2 | package PB;
3 |
4 | enum TAttribType
5 | {
6 | INVALID_ATTRIB = 0;
7 |
8 | ID = 2001001 ;
9 | LEVEL_UP_EXP_INT = 2001002 ;
10 | NAME_STRING = 2001003 ;
11 | LIFE_INT = 2001004 ;
12 | LIFE_CURR_INT = 2001005 ;
13 |
14 | };
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/BaseService/script/DataTable/proto/define_pro.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto2";
2 | package PB;
3 |
4 | enum TEvent
5 | {
6 | EventInvalid = 0; // 无效事件
7 | EventPlayerUp = 2; // 玩家升级
8 | EventCostMoney = 40; // 消费金钱
9 | EventLogin = 46; // 玩家登录
10 | };
11 |
12 |
13 | /// 标识占据第几位 0-63
14 | enum TPlayerFlagBit
15 | {
16 | PLAYER_FLAG_TEST_0 = 0; // 玩家第一次做xx事的标识位
17 | PLAYER_FLAG_FIRST_CARD_ONE = 1; //
18 | PLAYER_FLAG_FIRST_CARD_TEN = 2; //
19 |
20 | };
21 |
22 | enum TErrorType
23 | {
24 | INVALID_TYPE = 0;
25 |
26 | ACCOUNT_LOGGED = 1;
27 | SERVER_FULL = 2;
28 | SERVER_NOT_OPEN = 3;
29 | TEXT_SUCESS = 4;
30 | TEXT_FAIL = 5;
31 | PWD_ERROR = 6;
32 | PLAYER_ONLINE_TO_FES = 7;
33 | PLAYER_EXISTS = 8;
34 | PLAYER_RELOAD = 9;
35 | SUCESS = 23;
36 | NO_AUTH_TYPE = 24;
37 | CONFIG_NOT_FOUND = 33; // 配置未找到
38 | NOT_ENOUGH_MONEY = 37; // 金币不足
39 |
40 | PLAYER_BASE_ERROR = 128; // 玩家基本数据不正确
41 |
42 | };
43 |
44 | enum TGender
45 | {
46 | MALE = 0; // 男性
47 | FEMALE = 1; // 女性
48 | };
49 |
50 |
51 | enum TCardsType
52 | {
53 | CardsNone = 0; // 无色
54 | CardsSpade = 1; // 黑桃
55 | CardsHearts = 2; // 红桃
56 | CardsPlumBlossom = 3; // 梅花
57 | CardsDiamond = 4; // 方片
58 | };
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
--------------------------------------------------------------------------------
/BaseService/script/DataTable/proto/msg_client.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto2";
2 | package PB;
3 |
4 | import "define_pro.proto";
5 |
6 | message MsgLogin
7 | {
8 | optional string Version = 1;
9 | optional string Channel = 2;
10 | optional string AppName = 3;
11 | optional string User = 4;
12 | optional string NonceStr = 5;
13 | optional string Token = 6;
14 | optional uint64 Timestamp = 7;
15 | optional uint64 UID = 8;
16 | optional string RoomType = 9;
17 |
18 |
19 | }
20 |
21 | message MsgPlayerInfo
22 | {
23 | optional uint64 UID = 1;
24 | optional string Nickname = 2;
25 | optional uint32 Portrait = 3;
26 | optional uint64 Money = 4;
27 | optional uint64 RMB = 5;
28 | optional uint32 Main = 6;
29 | optional uint64 FlagBit = 7;
30 | }
31 |
32 | message MsgCreatePrivateRoom
33 | {
34 | optional string room_type = 1;
35 | }
36 |
37 | message MsgEnterPrivateRoom
38 | {
39 | optional uint64 room_id = 1;
40 | optional string room_type = 2;
41 | optional string app_name = 3;
42 | optional uint32 game_versione = 4;
43 | }
44 |
45 | message MsgCard
46 | {
47 | optional uint32 card = 1;
48 | }
49 |
50 | message MsgCards
51 | {
52 | repeated uint32 cards = 1;
53 | }
54 |
55 | message MsgInt
56 | {
57 | optional int64 value = 1;
58 | }
59 |
60 | message MsgBool
61 | {
62 | optional bool value = 1;
63 | }
64 |
65 | message MsgString
66 | {
67 | optional string str = 1;
68 | }
69 |
70 | message MsgError
71 | {
72 | optional uint32 errno = 1;
73 | optional uint64 value = 2;
74 | }
75 |
76 |
--------------------------------------------------------------------------------
/BaseService/script/DataTable/proto/msg_service.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto2";
2 | package PB;
3 |
4 | message MsgGameType
5 | {
6 | optional string Type = 1;
7 | optional uint32 Max = 2;
8 | optional uint32 Curr = 3;
9 |
10 | }
11 |
12 | message MsgServiceInfo
13 | {
14 | repeated MsgGameType RoomList = 1;
15 | optional uint32 MaxPlayer = 2;
16 | optional uint32 CurrPlayer = 3;
17 | optional uint32 ServiceID = 4;
18 | optional string ServiceName = 5;
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/BaseService/script/Framework/CJsonUtil.lua:
--------------------------------------------------------------------------------
1 | local json = require "cjson"
2 |
3 | -- Various common routines used by the Lua CJSON package
4 | --
5 | -- Mark Pulford
6 |
7 | -- Determine with a Lua table can be treated as an array.
8 | -- Explicitly returns "not an array" for very sparse arrays.
9 | -- Returns:
10 | -- -1 Not an array
11 | -- 0 Empty table
12 | -- >0 Highest index in the array
13 | local function is_array(table)
14 | local max = 0
15 | local count = 0
16 | for k, v in pairs(table) do
17 | if type(k) == "number" then
18 | if k > max then max = k end
19 | count = count + 1
20 | else
21 | return -1
22 | end
23 | end
24 | if max > count * 2 then
25 | return -1
26 | end
27 |
28 | return max
29 | end
30 |
31 | local serialise_value
32 |
33 | local function serialise_table(value, indent, depth)
34 | local spacing, spacing2, indent2
35 | if indent then
36 | spacing = "\n" .. indent
37 | spacing2 = spacing .. " "
38 | indent2 = indent .. " "
39 | else
40 | spacing, spacing2, indent2 = " ", " ", false
41 | end
42 | depth = depth + 1
43 | if depth > 50 then
44 | return "Cannot serialise any further: too many nested tables"
45 | end
46 |
47 | local max = is_array(value)
48 |
49 | local comma = false
50 | local fragment = { "{" .. spacing2 }
51 | if max > 0 then
52 | -- Serialise array
53 | for i = 1, max do
54 | if comma then
55 | table.insert(fragment, "," .. spacing2)
56 | end
57 | table.insert(fragment, serialise_value(value[i], indent2, depth))
58 | comma = true
59 | end
60 | elseif max < 0 then
61 | -- Serialise table
62 | for k, v in pairs(value) do
63 |
64 | if k ~= "class" then
65 | if comma then
66 | table.insert(fragment, "," .. spacing2)
67 | end
68 | table.insert(fragment,
69 | --("[%s] = %s"):format(serialise_value(k, indent2, depth),
70 | ("%s : %s"):format(serialise_value(k, indent2, depth),
71 | serialise_value(v, indent2, depth)))
72 | comma = true
73 | end
74 | end
75 | end
76 | table.insert(fragment, spacing .. "}")
77 |
78 | return table.concat(fragment)
79 | end
80 |
81 | function serialise_value(value, indent, depth)
82 | if indent == nil then indent = "" end
83 | if depth == nil then depth = 0 end
84 |
85 | if value == json.null then
86 | return "json.null"
87 | elseif type(value) == "string" then
88 | return ("%q"):format(value)
89 | elseif type(value) == "nil" or type(value) == "number" or
90 | type(value) == "boolean" then
91 | return tostring(value)
92 | elseif type(value) == "table" then
93 | return serialise_table(value, indent, depth)
94 | else
95 | return "\"<" .. type(value) .. ">\""
96 | end
97 | end
98 |
99 | local function file_load(filename)
100 | local file
101 | if filename == nil then
102 | file = io.stdin
103 | else
104 | local err
105 | file, err = io.open(filename, "rb")
106 | if file == nil then
107 | error(("Unable to read '%s': %s"):format(filename, err))
108 | end
109 | end
110 | local data = file:read("*a")
111 |
112 | if filename ~= nil then
113 | file:close()
114 | end
115 |
116 | if data == nil then
117 | error("Failed to read " .. filename)
118 | end
119 |
120 | return data
121 | end
122 |
123 | local function file_save(filename, data)
124 | local file
125 | if filename == nil then
126 | file = io.stdout
127 | else
128 | local err
129 | file, err = io.open(filename, "wb")
130 | if file == nil then
131 | error(("Unable to write '%s': %s"):format(filename, err))
132 | end
133 | end
134 | file:write(data)
135 | if filename ~= nil then
136 | file:close()
137 | end
138 | end
139 |
140 | local function compare_values(val1, val2)
141 | local type1 = type(val1)
142 | local type2 = type(val2)
143 | if type1 ~= type2 then
144 | return false
145 | end
146 |
147 | -- Check for NaN
148 | if type1 == "number" and val1 ~= val1 and val2 ~= val2 then
149 | return true
150 | end
151 |
152 | if type1 ~= "table" then
153 | return val1 == val2
154 | end
155 |
156 | -- check_keys stores all the keys that must be checked in val2
157 | local check_keys = {}
158 | for k, _ in pairs(val1) do
159 | check_keys[k] = true
160 | end
161 |
162 | for k, v in pairs(val2) do
163 | if not check_keys[k] then
164 | return false
165 | end
166 |
167 | if not compare_values(val1[k], val2[k]) then
168 | return false
169 | end
170 |
171 | check_keys[k] = nil
172 | end
173 | for k, _ in pairs(check_keys) do
174 | -- Not the same if any keys from val1 were not found in val2
175 | return false
176 | end
177 | return true
178 | end
179 |
180 | local test_count_pass = 0
181 | local test_count_total = 0
182 |
183 | local function run_test_summary()
184 | return test_count_pass, test_count_total
185 | end
186 |
187 | local function run_test(testname, func, input, should_work, output)
188 | local function status_line(name, status, value)
189 | local statusmap = { [true] = ":success", [false] = ":error" }
190 | if status ~= nil then
191 | name = name .. statusmap[status]
192 | end
193 | print(("[%s] %s"):format(name, serialise_value(value, false)))
194 | end
195 |
196 | local result = {}
197 | local tmp = { pcall(func, unpack(input)) }
198 | local success = tmp[1]
199 | for i = 2, table.maxn(tmp) do
200 | result[i - 1] = tmp[i]
201 | end
202 |
203 | local correct = false
204 | if success == should_work and compare_values(result, output) then
205 | correct = true
206 | test_count_pass = test_count_pass + 1
207 | end
208 | test_count_total = test_count_total + 1
209 |
210 | local teststatus = { [true] = "PASS", [false] = "FAIL" }
211 | print(("==> Test [%d] %s: %s"):format(test_count_total, testname,
212 | teststatus[correct]))
213 |
214 | status_line("Input", nil, input)
215 | if not correct then
216 | status_line("Expected", should_work, output)
217 | end
218 | status_line("Received", success, result)
219 | print()
220 |
221 | return correct, result
222 | end
223 |
224 | local function run_test_group(tests)
225 | local function run_helper(name, func, input)
226 | if type(name) == "string" and #name > 0 then
227 | print("==> " .. name)
228 | end
229 | -- Not a protected call, these functions should never generate errors.
230 | func(unpack(input or {}))
231 | print()
232 | end
233 |
234 | for _, v in ipairs(tests) do
235 | -- Run the helper if "should_work" is missing
236 | if v[4] == nil then
237 | run_helper(unpack(v))
238 | else
239 | run_test(unpack(v))
240 | end
241 | end
242 | end
243 |
244 | -- Run a Lua script in a separate environment
245 | local function run_script(script, env)
246 | local env = env or {}
247 | local func
248 |
249 | -- Use setfenv() if it exists, otherwise assume Lua 5.2 load() exists
250 | if _G.setfenv then
251 | func = loadstring(script)
252 | if func then
253 | setfenv(func, env)
254 | end
255 | else
256 | func = load(script, nil, nil, env)
257 | end
258 |
259 | if func == nil then
260 | error("Invalid syntax.")
261 | end
262 | func()
263 |
264 | return env
265 | end
266 |
267 | -- Export functions
268 | return {
269 | serialise_value = serialise_value,
270 | file_load = file_load,
271 | file_save = file_save,
272 | compare_values = compare_values,
273 | run_test_summary = run_test_summary,
274 | run_test = run_test,
275 | run_test_group = run_test_group,
276 | run_script = run_script
277 | }
278 |
279 | -- vi:ai et sw=4 ts=4:
280 |
--------------------------------------------------------------------------------
/BaseService/script/Framework/Class.lua:
--------------------------------------------------------------------------------
1 | function class(classname, super)
2 | local superType = type(super)
3 | local cls
4 |
5 | if superType ~= "function" and superType ~= "table" then
6 | superType = nil
7 | super = nil
8 | end
9 |
10 | if superType == "function" or (super and super.__ctype == 1) then
11 | -- inherited from native C++ Object
12 | cls = {}
13 |
14 | if superType == "table" then
15 | -- copy fields from super
16 | for k,v in pairs(super) do cls[k] = v end
17 | cls.__create = super.__create
18 | cls.super = super
19 | else
20 | cls.__create = super
21 | cls.ctor = function() end
22 | end
23 |
24 | cls.__cname = classname
25 | cls.__ctype = 1
26 |
27 | function cls.new(...)
28 | local instance = cls.__create(...)
29 | -- copy fields from class to native object
30 | for k,v in pairs(cls) do instance[k] = v end
31 | instance.class = cls
32 | instance:ctor(...)
33 | return instance
34 | end
35 |
36 | else
37 | -- inherited from Lua Object
38 | if super then
39 | cls = {}
40 | setmetatable(cls, {__index = super})
41 | cls.super = super
42 | else
43 | cls = {ctor = function() end}
44 | end
45 |
46 | cls.__cname = classname
47 | cls.__ctype = 2 -- lua
48 | cls.__index = cls
49 |
50 | function cls.new(...)
51 | local instance = setmetatable({}, cls)
52 | instance.class = cls
53 | instance:ctor(...)
54 | return instance
55 | end
56 | end
57 |
58 | return cls
59 | end
--------------------------------------------------------------------------------
/BaseService/script/Framework/Event/EventController.lua:
--------------------------------------------------------------------------------
1 | --=========================================================
2 | -- 消息派发
3 | --=========================================================
4 | EventController = singleton("EventController");
5 |
6 | function EventController:Init()
7 | self._MessageQue = {};
8 | end
9 |
10 | function EventController:RegisterEvent(messageType, callback)
11 | --if EventName[messageType] == nil or type(callback) ~= "function" then
12 | -- return
13 | --end
14 | if (messageType == nil) then
15 | logError("EventController.RegisterEvent messageType == nil");
16 | return;
17 | end
18 |
19 | if (callback == nil) then
20 | local sError = "EventController.RegisterEvent callback == nil ";
21 | if (nil ~= messageType) then
22 | sError = sError .. "messageType = "..messageType;
23 | end
24 | logError(sError);
25 | return;
26 | end
27 |
28 | if self._MessageQue[messageType] == nil then
29 | self._MessageQue[messageType] = {}
30 | end
31 |
32 | local index = #self._MessageQue[messageType]; -- table.getn => # lua5.3
33 | self._MessageQue[messageType][index+1] = callback
34 | end
35 |
36 | function EventController:TriggerEvent( msg_type, ... )
37 |
38 | if self._MessageQue[msg_type] == nil then
39 | return
40 | end
41 | for i,v in pairs(self._MessageQue[msg_type]) do
42 | if (v ~= nil)then
43 | v(...)
44 | else
45 | end
46 | end
47 |
48 | end
49 |
50 | function EventController:RemoveEvent(messageType,callback)
51 | --if EventName[messageType] == nil or type(callback) ~= "function" then
52 | -- return
53 | --end
54 | for i,v in pairs(self._MessageQue[messageType]) do
55 | if callback == v then
56 | table.remove(self._MessageQue[messageType],i)
57 | return
58 | end
59 | end
60 | end
61 |
62 | return EventController
63 |
--------------------------------------------------------------------------------
/BaseService/script/Framework/Event/EventRegister.lua:
--------------------------------------------------------------------------------
1 | --=========================================================
2 | -- 消息注册管理
3 | --=========================================================
4 | local EventRegister = class("EventRegister");
5 |
6 | -- 构造函数
7 | function EventRegister:ctor()
8 | self._EventCallBackTable = {}; -- 事件回调表
9 | end
10 |
11 |
12 | -- 注册某个事件
13 | function EventRegister:RegisterEvent(Name, Obj, Func)
14 | if (nil == Name) then
15 | logError("RegisterEvent Name == nil!")
16 | return;
17 | end
18 |
19 | local Handler = handler(Obj, Func);
20 | local EventTable = self:GetEventRegisterTable(Name);
21 | if (nil ~= EventTable) then
22 | local idx = #EventTable;
23 | EventTable[idx + 1] = Handler;
24 | else
25 | local v = {};
26 | v[1] = Handler;
27 | self._EventCallBackTable[Name] = v;
28 | end
29 |
30 | EventController.Instance():RegisterEvent(Name, Handler);
31 | end
32 |
33 | -- 获取事件注册表
34 | function EventRegister:GetEventRegisterTable(Name)
35 | for k,v in pairs(self._EventCallBackTable) do
36 | if(k == Name) then
37 | return v;
38 | end
39 | end
40 | return nil;
41 | end
42 |
43 | -- 删除所有事件
44 | function EventRegister:UnRegisterAllEvent()
45 | for k,v in pairs(self._EventCallBackTable) do
46 | for i = 1, #v do
47 | EventController.Instance():RemoveEvent(k, v[i]);
48 | end
49 | end
50 | self._EventCallBackTable = {};
51 | end
52 |
53 |
54 | return EventRegister;
--------------------------------------------------------------------------------
/BaseService/script/Framework/Event/EventTrigger.lua:
--------------------------------------------------------------------------------
1 | EventTrigger = {};
2 | local this = EventTrigger;
3 |
4 | function EventTrigger.OnEvent( msg_type, ... )
5 | EventController.Instance():TriggerEvent( msg_type, ... );
6 | end
7 |
8 |
9 |
--------------------------------------------------------------------------------
/BaseService/script/Framework/InitFramework.lua:
--------------------------------------------------------------------------------
1 | --=========================================================
2 | -- 初始化基础通用工具
3 | --=========================================================
4 |
5 | local BasePath = Misc.GetBasePath() .. "/script/";
6 | package.path = package.path .. BasePath .. "Framework/?.lua;";
7 | package.path = package.path .. BasePath .. "Framework/Event/?.lua;";
8 | package.path = package.path .. BasePath .. "Framework/Net/?.lua;";
9 |
10 |
11 | protobuf = require "protobuf"
12 |
13 | addr = io.open( BasePath.."DataTable/ProtoMsg.pb", "rb")
14 | buffer = addr:read "*a"
15 | addr:close()
16 | protobuf.register(buffer)
17 | protobuf.decode("google.protobuf.FileDescriptorSet", buffer)
18 |
19 |
20 | Json = require "cjson"
21 | JsonUtil = require "CJsonUtil"
22 |
23 |
24 | -- 工具库
25 | require("Class")
26 | require("functions")
27 |
28 | require("Map")
29 | require("MapMap")
30 |
31 | --require ("bit")
32 |
33 | require("Net/NetWorkHandler")
34 | require("Net/BaseService")
35 | require("TimerMgr");
36 | require("Event/EventTrigger");
37 |
38 |
39 | --List = require("Common/List")
40 | --Queue = require("Common/Queue")
41 | --Map = require("Common/Map")
42 |
43 | -- protobuf
44 | --require ("Common/ProtoBuffer/define_attrib_pb")
45 |
46 |
47 | -- LuaFramework --
48 | IDGenerate = bin_types.IDGenerate;
49 | MysqlStmt = bin_types.MysqlStmt;
50 | MysqlConn = bin_types.MysqlConn;
51 | MysqlResult = bin_types.MysqlResult;
52 | CMessage = bin_types.LuaMessage.NewInstance;
53 |
54 | --[[
55 | Util = LuaFramework.Util;
56 | NativeUtil = LuaFramework.NativeUtil;
57 | AppConst = LuaFramework.AppConst;
58 | LuaHelper = LuaFramework.LuaHelper;
59 | NetMessage = LuaFramework.NetMessage;
60 | RecordNodeTable = LuaFramework.RecordNodeTable;
61 |
62 | -- LuaHelper --
63 | NetWorkHelper = LuaHelper.GetNetManager();
64 | GameManager = LuaHelper.GetGameManager();
65 | PoolManager = LuaHelper.GetPoolManager();
66 | LuaManager = LuaHelper.GetLuaManger();
67 |
68 | --]]
69 |
70 | -- 表
71 | --require("Event/EventType")
72 |
73 |
74 |
75 | -- 工具
76 |
77 |
78 | --LSModule = require("SDK/LService/LSModule")
79 | --WebModule = require("SDK/Web/WebModule")
80 | --HttpClient = require("Common/Net/HttpClient")
81 |
82 | EventController = require("Event/EventController")
83 | --ServerManager = require("Net/ServerManager")
84 | EventRegister = require("Event/EventRegister")
85 | CallbackServer = require("Net/CallbackServer");
86 | StateMachine = require("SimpleStateMachine");
87 |
88 |
89 |
90 |
91 |
92 | -- 初始化单例
93 | function OnInitFramework()
94 | EventController.Instance():Init()
95 | TimerMgr:Init(os.clock()*1000);
96 | end
97 |
98 |
99 | OnInitFramework();
100 |
--------------------------------------------------------------------------------
/BaseService/script/Framework/List.lua:
--------------------------------------------------------------------------------
1 | local List = class("List");
2 |
3 | -- 构造函数
4 | function List:ctor()
5 | -- body
6 | -- 元素列表
7 | self._list = {};
8 | -- print(self._list);
9 | end
10 |
11 |
12 |
13 | -- 添加一个元素
14 | function List:Push(value)
15 | -- body
16 |
17 | table.insert(self._list, value);
18 | end
19 |
20 | -- 插入一个元素
21 | function List:Insert(idx, value)
22 | table.insert(self._list, idx, value);
23 | end
24 |
25 | -- 获取一个元素
26 | function List:Get(index)
27 | -- body
28 |
29 | if self:Count() <= 0 or index == nil or type(index) ~= "number" then
30 | --todo
31 |
32 | return nil;
33 | end
34 |
35 | return self._list[index];
36 | end
37 |
38 | -- 获取最后一个元素
39 | function List:GetLast()
40 | return self:Get(self:Count());
41 | end
42 |
43 | -- 获取第一个元素
44 | function List:GetFirst()
45 | return self:Get(1);
46 | end
47 |
48 | -- 删除对象
49 | function List:Remove(value)
50 | if value == nil then
51 | return
52 | end
53 | -- body
54 | for i=1,self:Count() do
55 | local nValue = self._list[i];
56 | if nValue == value then
57 | --todo
58 | table.remove(self._list, i);
59 | i = i - 1;
60 | end
61 | end
62 | end
63 |
64 |
65 | --删除单个对象
66 | function List:RemoveOne(value)
67 | if value == nil then
68 | return
69 | end
70 | for i=1,self:Count() do
71 | local nValue = self._list[i];
72 | if nValue == value then
73 | --todo
74 | table.remove(self._list, i);
75 | break;
76 | end
77 | end
78 | end
79 |
80 | -- 根据索引删除对象
81 | function List:RemoveByIndex(idx)
82 | if (idx < 1 or idx > self:Count()) then
83 | return;
84 | end
85 |
86 | table.remove(self._list, idx);
87 | end
88 |
89 | -- 自定义函数删除
90 | -- 注意会把nil一起删除掉,如果不需要可以改下
91 | function List:RemoveIf(fun, ...)
92 | local m = 1;
93 | while m <= self:Count() do
94 | local nValue = self._list[m];
95 | if (nil ~= nValue) then
96 | if fun(nValue, ...) then
97 | table.remove(self._list, m);
98 | else
99 | m = m + 1;
100 | end
101 | else
102 | table.remove(self._list, m);
103 | end
104 | end
105 | end
106 |
107 | -- 删除所有对象
108 | function List:RemoveAll(Value)
109 | local m = 1;
110 | while m <= self:Count() do
111 | local nValue = self._list[m];
112 | if (nValue == Value) then
113 | table.remove(self._list, m);
114 | else
115 | m = m + 1;
116 | end
117 | end
118 | end
119 |
120 | -- 是否有某个元素
121 | function List:Contain(value)
122 | for i=1,self:Count() do
123 | local nValue = self._list[i];
124 | if nValue == value then
125 | return true;
126 | end
127 | end
128 |
129 | return false;
130 | end
131 |
132 | -- 替换列表中的元素
133 | -- 下标为空替换失败
134 | function List:ReplaceValue( index , value )
135 | local nValue = self._list[index];
136 | if nil ~= nValue then
137 | self._list[index] = value;
138 | end
139 | end
140 |
141 | --获取列表中元素的个数
142 | function List:GetValueCount(value)
143 | local Count = 0;
144 | for i=1,self:Count() do
145 | local nValue = self._list[i];
146 | if nValue == value then
147 | Count = Count + 1;
148 | end
149 | end
150 | return Count;
151 | end
152 |
153 | -- 获取元素的索引
154 | -- 找不到返回-1
155 | function List:IndexOf(value)
156 | for i = 1,self:Count() do
157 | local nValue = self._list[i];
158 | if nValue == value then
159 | return i;
160 | end
161 | end
162 |
163 | return -1;
164 | end
165 |
166 | -- 遍历所有成员
167 | function List:ForEach(fun, ...)
168 | -- body
169 | for k,v in pairs(self._list) do
170 | fun(v, ...)
171 | end
172 | end
173 |
174 | -- 数量
175 | function List:Count()
176 | -- body
177 | return #self._list;
178 | end
179 |
180 | -- 克隆一个
181 | function List:Clone()
182 | local t = List:new()
183 |
184 | for i, v in pairs(self._list) do
185 | t:Push(v)
186 | end
187 |
188 | return t
189 | end
190 |
191 | -- list赋值
192 | function List:Assign(InList)
193 | self._list = {};
194 | for i = 1, InList:Count() do
195 | self._list[i] = InList:Get(i);
196 | end
197 | end
198 |
199 | -- 追加
200 | function List:Append(InList)
201 | local CurCount = self:Count();
202 | for i = 1, InList:Count() do
203 | self._list[i + CurCount] = InList:Get(i);
204 | end
205 | end
206 |
207 | -- 清除
208 | function List:Clear()
209 | -- body
210 | self._list={};
211 | end
212 |
213 | -- 排序
214 | function List:Sort( Action )
215 | table.sort( self._list, Action );
216 | end
217 |
218 |
219 | -- 反序
220 | function List:Reverse()
221 | local TmpTab = {};
222 | local k = 1;
223 | for i = #self._list, 1, -1 do
224 | TmpTab[k] = self._list[i];
225 | k = k + 1;
226 | end
227 | for i = 1, #TmpTab do
228 | self._list[i] = TmpTab[i];
229 | end
230 | TmpTab = nil;
231 | end
232 |
233 | -- 求包含的元素个数
234 | function List:NumsOf(inValue)
235 | local Nums = 0;
236 | for i = 1,self:Count() do
237 | local nValue = self._list[i];
238 | if nValue == inValue then
239 | Nums = Nums + 1;
240 | end
241 | end
242 |
243 | return Nums;
244 | end
245 |
246 | -- 返回符合条件的项
247 | function List:GetIf(fun, ...)
248 | for i = 1, self:Count() do
249 | local Value = self:Get(i);
250 | if (nil ~= Value) then
251 | if fun(Value, ...) then
252 | return Value;
253 | end
254 | end
255 | end
256 |
257 | return nil;
258 | end
259 |
260 | -- 返回符合条件项的数量
261 | function List:NumsIf(fun, ...)
262 | local Nums = 0;
263 | for i = 1, self:Count() do
264 | local Value = self:Get(i);
265 | if (nil ~= Value) then
266 | if fun(Value, ...) then
267 | Nums = Nums + 1;
268 | end
269 | end
270 | end
271 |
272 | return Nums;
273 | end
274 |
275 | -- 返回所有符合条件的所有项
276 | function List:GetIfAll(fun, ...)
277 | local ret = {};
278 | for i = 1, self:Count() do
279 | local Value = self:Get(i);
280 | if (nil ~= Value) then
281 | if fun(Value, ...) then
282 | table.insert(ret, Value);
283 | end
284 | end
285 | end
286 |
287 | return ret;
288 | end
289 |
290 | return List;
--------------------------------------------------------------------------------
/BaseService/script/Framework/Map.lua:
--------------------------------------------------------------------------------
1 | Map = class("Map")
2 |
3 | local this = Map
4 |
5 | function this:ctor()
6 | self._map = {};
7 | self.count = 0
8 | end
9 |
10 | function this:GetTable()
11 | return self._map;
12 | end
13 |
14 | -- Map 插入新值
15 | function this:Insert(k,v)
16 | if nil == self._map[k] then
17 | self._map[k] = v
18 | self.count = self.count + 1
19 | end
20 | end
21 |
22 | -- Map 插入新值并且切换旧值
23 | function this:Replace(k,v)
24 | if nil == self._map[k] then
25 | self._map[k] = v;
26 | self.count = self.count + 1;
27 | else
28 | self._map[k] = v;
29 | end
30 | end
31 |
32 | function this:Remove(k)
33 | if nil ~= self._map[k] then
34 | self._map[k] = nil
35 | if self.count >0 then
36 | self.count = self.count - 1
37 | end
38 | end
39 | end
40 |
41 | function this:ForEachRemove(field, value)
42 |
43 | local newT = {}
44 |
45 | for k,v in pairs(self._map) do
46 | if v[field]~=value then
47 | newT[k] = v;
48 | end
49 | end
50 |
51 | self._map = newT;
52 | end
53 |
54 | function this:Find(k)
55 | local value = nil
56 | if nil ~= self._map[k] then
57 | value = self._map[k]
58 | end
59 | return value
60 | end
61 |
62 | function this:Clear()
63 | for k,_ in pairs(self._map) do
64 | if nil ~= self._map[k] then
65 | self._map[k] = nil
66 | end
67 | end
68 | self.count = 0
69 | end
70 |
71 |
72 | -- 遍历所有成员
73 | function this:ForEach(fun, ...)
74 | -- body
75 | for k,v in pairs(self._map) do
76 | fun(k, v, ...)
77 | end
78 | end
79 |
80 | -- Map 获取字典的count
81 | function this:Count()
82 | return self.count;
83 | end
84 |
85 | return Map;
86 |
87 |
88 | --local characters = Map:new()
89 | --characters:Insert("name1"," this Name:123")
90 | --characters:Replace("name1"," this Name:2" )
91 | --local name2 = characters:Find("name1")
92 | --print(name2)
93 | --print(characters.count)
94 | --for k,v in pairs(characters) do
95 | --print(k,v)
96 | --end
--------------------------------------------------------------------------------
/BaseService/script/Framework/MapMap.lua:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li9chuan/EgretWebSocket/d72c82d6c26d77851c705444e7c9f0143fc249d8/BaseService/script/Framework/MapMap.lua
--------------------------------------------------------------------------------
/BaseService/script/Framework/MiddleClass.lua:
--------------------------------------------------------------------------------
1 | -- Example
2 | -- local class = require 'middleclass'
3 | -- local Fruit = class('Fruit') -- 'Fruit' is the class' name
4 |
5 | -- function Fruit:initialize(sweetness)
6 | -- self.sweetness = sweetness
7 | -- end
8 |
9 | -- Fruit.static.sweetness_threshold = 5 -- class variable (also admits methods)
10 |
11 | -- function Fruit:isSweet()
12 | -- return self.sweetness > Fruit.sweetness_threshold
13 | -- end
14 |
15 | -- local Lemon = class('Lemon', Fruit) -- subclassing
16 |
17 | -- function Lemon:initialize()
18 | -- Fruit.initialize(self, 1) -- invoking the superclass' initializer
19 | -- end
20 |
21 | -- local lemon = Lemon:new() or Lemon()
22 | -- print(lemon:isSweet()) -- false
23 | --
24 | local middleclass = {}
25 |
26 | local function _createIndexWrapper(aClass, f)
27 | if f == nil then
28 | return aClass.__instanceDict
29 | else
30 | return function(self, name)
31 | local value = aClass.__instanceDict[name]
32 |
33 | if value ~= nil then
34 | return value
35 | elseif type(f) == "function" then
36 | return (f(self, name))
37 | else
38 | return f[name]
39 | end
40 | end
41 | end
42 | end
43 |
44 | local function _propagateInstanceMethod(aClass, name, f)
45 | f = name == "__index" and _createIndexWrapper(aClass, f) or f
46 | aClass.__instanceDict[name] = f
47 |
48 | for subclass in pairs(aClass.subclasses) do
49 | if rawget(subclass.__declaredMethods, name) == nil then
50 | _propagateInstanceMethod(subclass, name, f)
51 | end
52 | end
53 | end
54 |
55 | local function _declareInstanceMethod(aClass, name, f)
56 | aClass.__declaredMethods[name] = f
57 |
58 | if f == nil and aClass.super then
59 | f = aClass.super.__instanceDict[name]
60 | end
61 |
62 | _propagateInstanceMethod(aClass, name, f)
63 | end
64 |
65 | local function _tostring(self) return "class " .. self.name end
66 | local function _call(self, ...) return self:new(...) end
67 |
68 | local function _createClass(name, super)
69 | local dict = {}
70 | dict.__index = dict
71 |
72 | local aClass = {name = name, super = super, static = {},
73 | __instanceDict = dict, __declaredMethods = {},
74 | subclasses = setmetatable({}, {__mode = 'k'})}
75 |
76 | if super then
77 | setmetatable(aClass.static, {__index = function(_, k) return rawget(dict, k) or super.static[k] end})
78 | else
79 | setmetatable(aClass.static, {__index = function(_, k) return rawget(dict, k) end})
80 | end
81 |
82 | setmetatable(aClass, {__index = aClass.static, __tostring = _tostring,
83 | __call = _call, __newindex = _declareInstanceMethod})
84 |
85 | return aClass
86 | end
87 |
88 | local function _includeMixin(aClass, mixin)
89 | assert(type(mixin) == 'table', "mixin must be a table")
90 |
91 | for name, method in pairs(mixin) do
92 | if name ~= "included" and name ~= "static" then aClass[name] = method end
93 | end
94 |
95 | for name, method in pairs(mixin.static or {}) do
96 | aClass.static[name] = method
97 | end
98 |
99 | if type(mixin.included) == "function" then mixin:included(aClass) end
100 | return aClass
101 | end
102 |
103 | local DefaultMixin = {
104 | __tostring = function(self) return "instance of " .. tostring(self.class) end,
105 |
106 | initialize = function(self, ...) end,
107 |
108 | isInstanceOf = function(self, aClass)
109 | return type(aClass) == 'table' and (aClass == self.class or self.class:isSubclassOf(aClass))
110 | end,
111 |
112 | static = {
113 | allocate = function(self)
114 | assert(type(self) == 'table', "Make sure that you are using 'Class:allocate' instead of 'Class.allocate'")
115 | return setmetatable({class = self}, self.__instanceDict)
116 | end,
117 |
118 | new = function(self, ...)
119 | assert(type(self) == 'table', "Make sure that you are using 'Class:new' instead of 'Class.new'")
120 | local instance = self:allocate()
121 | instance:initialize(...)
122 | return instance
123 | end,
124 |
125 | subclass = function(self, name)
126 | assert(type(self) == 'table', "Make sure that you are using 'Class:subclass' instead of 'Class.subclass'")
127 | assert(type(name) == "string", "You must provide a name(string) for your class")
128 |
129 | local subclass = _createClass(name, self)
130 |
131 | for methodName, f in pairs(self.__instanceDict) do
132 | _propagateInstanceMethod(subclass, methodName, f)
133 | end
134 | subclass.initialize = function(instance, ...) return self.initialize(instance, ...) end
135 |
136 | self.subclasses[subclass] = true
137 | self:subclassed(subclass)
138 |
139 | return subclass
140 | end,
141 |
142 | subclassed = function(self, other) end,
143 |
144 | isSubclassOf = function(self, other)
145 | return type(other) == 'table' and
146 | type(self.super) == 'table' and
147 | (self.super == other or self.super:isSubclassOf(other))
148 | end,
149 |
150 | include = function(self, ...)
151 | assert(type(self) == 'table', "Make sure you that you are using 'Class:include' instead of 'Class.include'")
152 | for _, mixin in ipairs({...}) do _includeMixin(self, mixin) end
153 | return self
154 | end
155 | }
156 | }
157 |
158 | function middleclass.class(name, super)
159 | assert(type(name) == 'string', "A name (string) is needed for the new class")
160 | return super and super:subclass(name) or _includeMixin(_createClass(name), DefaultMixin)
161 | end
162 |
163 | setmetatable(middleclass, {__call = function(_, ...) return middleclass.class(...) end})
164 |
165 | return middleclass
166 |
--------------------------------------------------------------------------------
/BaseService/script/Framework/Net/BaseService.lua:
--------------------------------------------------------------------------------
1 | BaseService = {}
2 |
3 | function BaseService:Send( service_id, cmsg_or_type, proto_type, proto_msg )
4 |
5 | local param_type = type(cmsg_or_type)
6 |
7 | if param_type=="string" then
8 |
9 | local lua_msg = CMessage(cmsg_or_type);
10 |
11 | if type(proto_type)=="table" then -- send table => json str
12 | local json_str = Table2Json(proto_type);
13 | lua_msg:wstring(json_str);
14 | elseif type(proto_type)=="string" then -- send proto msg
15 | local proto_code = protobuf.encode(proto_type, proto_msg);
16 | lua_msg:wstring(proto_code);
17 | end
18 | ServerNet.Send( service_id, lua_msg );
19 |
20 | elseif param_type=="userdata" then -- send cmessage
21 | ServerNet.Send( service_id, cmsg_or_type );
22 | end
23 |
24 | end
25 |
26 | function BaseService:Broadcast( service_name, msg_out )
27 | ServerNet.Broadcast( service_name, msg_out );
28 | end
29 |
30 | function BaseService:SendToClient( player, cmsg_or_type, proto_type, proto_msg )
31 |
32 | if player==nil then
33 | return
34 | end
35 |
36 | local send_info = { player.ConFES, player.UID };
37 | local param_type = type(cmsg_or_type)
38 |
39 | if param_type=="string" then
40 |
41 | local lua_msg = CMessage(cmsg_or_type);
42 |
43 | if type(proto_type)=="table" then -- send table => json str
44 | local json_str = Table2Json(proto_type);
45 | lua_msg:wstring(json_str);
46 | nlwarning(json_str);
47 | elseif type(proto_type)=="string" then -- send proto msg
48 | local proto_code = protobuf.encode(proto_type, proto_msg);
49 | lua_msg:wstring(proto_code);
50 | end
51 | ServerNet.SendToClient( lua_msg, send_info );
52 |
53 | elseif param_type=="userdata" then -- send cmessage
54 | ServerNet.SendToClient( cmsg_or_type, send_info );
55 | end
56 |
57 | end
58 |
59 |
60 | return BaseService
61 |
62 |
--------------------------------------------------------------------------------
/BaseService/script/Framework/Net/CallbackServer.lua:
--------------------------------------------------------------------------------
1 | local CallbackServer = class("CallbackServer")
2 |
3 | function CallbackServer:ctor()
4 | self.Service = nil;
5 | self.ConnectCallbackEvent = "";
6 | self.DisConnectCallbackEvent = "";
7 | end
8 |
9 | function CallbackServer:Init( name, protocal )
10 | self.ConnectCallbackEvent = name .. "Con";
11 | self.DisConnectCallbackEvent = name .. "Dis";
12 |
13 | local listen_proc = string.lower(protocal);
14 | self.Service = bin_types.LuaCallbackServer.NewInstance( name, listen_proc );
15 | end
16 |
17 | function CallbackServer:Listen( port )
18 | self.Service:Listen(port);
19 | end
20 |
21 | function CallbackServer:LoadSslCA( ssl_ca )
22 | self.Service:LoadSslCA(ssl_ca);
23 | end
24 | function CallbackServer:LoadSslCrt( ssl_crt )
25 | self.Service:LoadSslCrt(ssl_crt);
26 | end
27 | function CallbackServer:LoadSslPrivateKey( ssl_prvkey )
28 | self.Service:LoadSslPrivateKey(ssl_prvkey);
29 | end
30 |
31 | function CallbackServer:SetClientData( client_data )
32 | self.Service:SetClientData( client_data );
33 | end
34 |
35 | function CallbackServer:RemoveClientData( uid )
36 | self.Service:RemoveClientData(uid);
37 | end
38 |
39 | function CallbackServer:Send( sock_id, msg_or_type, proto_type, proto_msg )
40 |
41 | local param_type = type(msg_or_type)
42 |
43 | if param_type=="string" then
44 | local lua_msg = CMessage(msg_or_type);
45 | if proto_type~=nil then
46 | local code = protobuf.encode(proto_type, proto_msg);
47 | lua_msg:wstring(code);
48 | end
49 | self.Service:Send( sock_id, lua_msg );
50 | else
51 | self.Service:Send( sock_id, msg_or_type );
52 | end
53 |
54 | end
55 |
56 | return CallbackServer
57 |
58 |
--------------------------------------------------------------------------------
/BaseService/script/Framework/Net/NetWorkHandler.lua:
--------------------------------------------------------------------------------
1 | NetWorkHandler = {};
2 | local this = NetWorkHandler;
3 |
4 | -- 收到连接,断开事件
5 | function NetWorkHandler.OnNetEvent( event_from, event_type, event_val )
6 | EventController.Instance():TriggerEvent( event_type, event_from, event_val );
7 | end
8 |
9 | -- 收到网络消息
10 | function NetWorkHandler.OnMessage( msg_from, lua_msg )
11 | print("recv msg:"..lua_msg:name());
12 | EventController.Instance():TriggerEvent( lua_msg:name(), msg_from, lua_msg );
13 | end
14 |
15 | function NetWorkHandler.OnError(state)
16 |
17 | end
18 |
19 |
--------------------------------------------------------------------------------
/BaseService/script/Framework/Net/TcpCbServer.lua:
--------------------------------------------------------------------------------
1 | local TcpCbServer = class("TcpCbServer")
2 |
3 | function TcpCbServer:ctor()
4 | self.Service = nil;
5 | self.ConnectCallbackEvent = "";
6 | self.DisConnectCallbackEvent = "";
7 | end
8 |
9 | function TcpCbServer:Listen( name, port )
10 | self.ConnectCallbackEvent = name .. "Connection";
11 | self.DisConnectCallbackEvent = name .. "DisConnection";
12 |
13 | self.Service = NetworkTcp.NewInstance(name, port);
14 | end
15 |
16 | function TcpCbServer:Send( sock_id, lua_msg )
17 | self.Service:Send( sock_id, lua_msg );
18 | end
19 |
20 | return TcpCbServer
21 |
22 |
--------------------------------------------------------------------------------
/BaseService/script/Framework/Net/WebSocketCbServer.lua:
--------------------------------------------------------------------------------
1 | local WebSocketCbServer = class("WebSocketCbServer")
2 |
3 | function WebSocketCbServer:ctor()
4 | self.Service = nil;
5 | self.ConnectCallbackEvent = "";
6 | self.DisConnectCallbackEvent = "";
7 | end
8 |
9 | function WebSocketCbServer:Listen( name, port )
10 | self.ConnectCallbackEvent = name .. "Connection";
11 | self.DisConnectCallbackEvent = name .. "DisConnection";
12 |
13 | self.Service = NetworkWebSocket.NewInstance(name, port);
14 | end
15 |
16 | function WebSocketCbServer:SetUIDMap( uid, sock_id )
17 | self.Service:SetUIDMap(uid, sock_id);
18 | end
19 |
20 | function WebSocketCbServer:RemoveUIDMap( uid )
21 | self.Service:RemoveUIDMap(uid);
22 | end
23 |
24 | function WebSocketCbServer:Send( sock_id, lua_msg )
25 | self.Service:Send( sock_id, lua_msg );
26 | end
27 |
28 | function WebSocketCbServer:SendPB( sock_id, msg_type, proto_type, proto_msg )
29 | local code = protobuf.encode(proto_type, proto_msg);
30 | local lua_msg = CMessage(msg_type);
31 | lua_msg:wstring(code);
32 | self.Service:Send( sock_id, lua_msg );
33 | end
34 |
35 | return WebSocketCbServer
36 |
37 |
--------------------------------------------------------------------------------
/BaseService/script/Framework/Queue.lua:
--------------------------------------------------------------------------------
1 |
2 | Queue = class("Queue")
3 |
4 | -- 构造函数
5 | function Queue:ctor()
6 | -- body
7 | -- 元素列表
8 | self._list = {};
9 | end
10 |
11 | -- 添加一个元素
12 | function Queue:Push(value)
13 | -- body
14 | if value ~= nil then
15 | --todo
16 | local nPos = #self._list + 1;
17 | table.insert(self._list, nPos, value);
18 | end
19 | end
20 |
21 | -- 弹出一个函数
22 | function Queue:Pop()
23 | -- body
24 | if self:Count() <= 0 then
25 | --todo
26 | return nil;
27 | end
28 |
29 | local nValue = self._list[1];
30 | table.remove(self._list, 1);
31 |
32 | return nValue;
33 | end
34 |
35 | -- 删除对象
36 | function Queue:Remove(value)
37 | -- body
38 | for i=1,self:Count() do
39 | local nValue = self._list[i];
40 | if v == value then
41 | --todo
42 | table.remove(self._list, i);
43 | i = i - 1;
44 | end
45 | end
46 | end
47 |
48 | -- 数量
49 | function Queue:Count()
50 | -- body
51 | return #self._list;
52 | end
53 |
54 | -- 清除
55 | function Queue:Clear()
56 | -- body
57 | self._list={};
58 | end
59 |
60 | return Queue;
--------------------------------------------------------------------------------
/BaseService/script/Framework/SimpleStateMachine.lua:
--------------------------------------------------------------------------------
1 | -- region *.lua
2 | -- Date
3 | -- 此文件由[BabeLua]插件自动生成
4 | --local class = require("MiddleClass")
5 |
6 | local simple_state_machine = class("SimpleStateMachine")
7 |
8 | simple_state_machine.VERSION = "2.2.0"
9 | -- the event transitioned successfully from one state to another
10 | simple_state_machine.SUCCEEDED = 1
11 | -- the event was successfull but no state transition was necessary
12 | simple_state_machine.NOTRANSITION = 2
13 | -- the event was cancelled by the caller in a beforeEvent callback
14 | simple_state_machine.CANCELLED = 3
15 | -- the event is asynchronous and the caller is in control of when the transition occurs
16 | simple_state_machine.PENDING = 4
17 | -- the event was failure
18 | simple_state_machine.FAILURE = 5
19 | -- caller tried to fire an event that was innapropriate in the current state
20 | simple_state_machine.INVALID_TRANSITION_ERROR = "INVALID_TRANSITION_ERROR"
21 | -- caller tried to fire an event while an async transition was still pending
22 | simple_state_machine.PENDING_TRANSITION_ERROR = "PENDING_TRANSITION_ERROR"
23 | -- caller provided callback function threw an exception
24 | simple_state_machine.INVALID_CALLBACK_ERROR = "INVALID_CALLBACK_ERROR"
25 |
26 | simple_state_machine.WILDCARD = "*"
27 | simple_state_machine.ASYNC = "ASYNC"
28 |
29 | function simple_state_machine:initialize()
30 | end
31 |
32 | function simple_state_machine:setup_state(cfg)
33 | assert(type(cfg) == "table", "simple_state_machine:setup_state() - invalid config")
34 |
35 | -- cfg.initial allow for a simple string,
36 | -- or an table with { state = "foo", event = "setup", defer = true|false }
37 | if type(cfg.initial) == "string" then
38 | self._initial = {state = cfg.initial}
39 | else
40 | self._initial = cfg.initial
41 | end
42 |
43 | self._terminal = cfg.terminal or cfg.final
44 | self._events = cfg.events or {}
45 | self._callbacks = cfg.callbacks or {}
46 | self._map = {}
47 | self._current = "none"
48 | self._in_transition = false
49 |
50 | if self._initial then
51 | self._initial.event = self._initial.event or "startup"
52 | self:_add_event({name = self._initial.event, from = "none", to = self._initial.state})
53 | end
54 |
55 | for _, event in ipairs(self._events) do
56 | self:_add_event(event)
57 | end
58 |
59 | if self._initial and not self._initial.defer then
60 | self:do_event(self._initial.event)
61 | end
62 |
63 | return self._target
64 | end
65 |
66 | function simple_state_machine:is_ready()
67 | return self._current ~= "none"
68 | end
69 |
70 | function simple_state_machine:get_state()
71 | return self._current
72 | end
73 |
74 | function simple_state_machine:is_state(state)
75 | if type(state) == "table" then
76 | for _, s in ipairs(state) do
77 | if s == self._current then
78 | return true
79 | end
80 | end
81 | return false
82 | else
83 | return self._current == state
84 | end
85 | end
86 |
87 | function simple_state_machine:can_do_event(event_name)
88 | return not self._in_transition and
89 | (self._map[event_name][self._current] ~= nil or self._map[event_name][simple_state_machine.WILDCARD] ~= nil)
90 | end
91 |
92 | function simple_state_machine:cannot_do_event(event_name)
93 | return not self:can_do_event(event_name)
94 | end
95 |
96 | function simple_state_machine:is_finished_state()
97 | return self:is_state(self._terminal)
98 | end
99 |
100 | function simple_state_machine:do_event_force(name, ...)
101 | local from = self._current
102 | local map = self._map[name]
103 | local to = (map[from] or map[simple_state_machine.WILDCARD]) or from
104 | local args = {...}
105 |
106 | local event = {
107 | name = name,
108 | from = from,
109 | to = to,
110 | args = args
111 | }
112 |
113 | if self._in_transition then
114 | self._in_transition = false
115 | end
116 |
117 | self:_before_event(event)
118 |
119 | if from == to then
120 | self:_after_event(event)
121 | return simple_state_machine.NOTRANSITION
122 | end
123 |
124 | self._current = to
125 | self:_enter_state(event)
126 | self:_change_state(event)
127 | self:_after_event(event)
128 | return simple_state_machine.SUCCEEDED
129 | end
130 |
131 | function simple_state_machine:do_event(name, ...)
132 | assert(self._map[name] ~= nil, string.format("simple_state_machine:DoEvent() - invalid event %s", tostring(name)))
133 |
134 | local from = self._current
135 | local map = self._map[name]
136 | local to = (map[from] or map[simple_state_machine.WILDCARD]) or from
137 | local args = {...}
138 |
139 | local event = {
140 | name = name,
141 | from = from,
142 | to = to,
143 | args = args,
144 | }
145 |
146 | if self._in_transition then
147 | self:_on_error(event, simple_state_machine.PENDING_TRANSITION_ERROR,
148 | "event " .. name .. " inappropriate because previous transition did not complete")
149 | return simple_state_machine.FAILURE
150 | end
151 |
152 | if self:cannot_do_event(name) then
153 | self:_on_error(event, simple_state_machine.INVALID_TRANSITION_ERROR,
154 | "event " .. name .. " inappropriate in current state " .. self._current)
155 | return simple_state_machine.FAILURE
156 | end
157 |
158 | if self:_before_event(event) == false then
159 | return simple_state_machine.CANCELLED
160 | end
161 |
162 | if from == to then
163 | self:_after_event(event)
164 | return simple_state_machine.NOTRANSITION
165 | end
166 |
167 | event.transition = function()
168 | self._in_transition = false
169 | self._current = to
170 | -- this method should only ever be called once
171 | self:_enter_state(event)
172 | self:_change_state(event)
173 | self:_after_event(event)
174 | return simple_state_machine.SUCCEEDED
175 | end
176 |
177 | event.cancel = function()
178 | -- provide a way for caller to cancel async transition if desired
179 | event.transition = nil
180 | self:_after_event(event)
181 | end
182 |
183 | self._in_transition = true
184 | local leave = self:_leave_state(event)
185 | if leave == false then
186 | event.transition = nil
187 | event.cancel = nil
188 | self._in_transition = false
189 | return simple_state_machine.CANCELLED
190 | elseif string.upper(tostring(leave)) == simple_state_machine.ASYNC then
191 | return simple_state_machine.PENDING
192 | else
193 | -- need to check in case user manually called transition()
194 | -- but forgot to return StateMachine.ASYNC
195 | if event.transition then
196 | return event.transition()
197 | else
198 | self._in_transition = false
199 | end
200 | end
201 | end
202 |
203 | function simple_state_machine:_add_event(event)
204 | local from = {}
205 | if type(event.from) == "table" then
206 | for _, name in ipairs(event.from) do
207 | from[name] = true
208 | end
209 | elseif event.from then
210 | from[event.from] = true
211 | else
212 | -- allow "wildcard" transition if "from" is not specified
213 | from[simple_state_machine.WILDCARD] = true
214 | end
215 |
216 | self._map[event.name] = self._map[event.name] or {}
217 | local map = self._map[event.name]
218 | for fromName, _ in pairs(from) do
219 | map[fromName] = event.to or fromName
220 | end
221 | end
222 |
223 | local function _do_callback(callback, event)
224 | if callback then
225 | return callback(event)
226 | end
227 | end
228 |
229 | function simple_state_machine:_before_any_event(event)
230 | return _do_callback(self._callbacks["onbeforeevent"], event)
231 | end
232 |
233 | function simple_state_machine:_after_any_event(event)
234 | return _do_callback(self._callbacks["onafterevent"], event)
235 | end
236 |
237 | function simple_state_machine:_leave_any_state(event)
238 | return _do_callback(self._callbacks["onleavestate"], event)
239 | end
240 |
241 | function simple_state_machine:_enter_any_state(event)
242 | return _do_callback(self._callbacks["onenterstate"] or self._callbacks["onstate"], event)
243 | end
244 |
245 | function simple_state_machine:_change_state(event)
246 | return _do_callback(self._callbacks["onchangestate"], event)
247 | end
248 |
249 | function simple_state_machine:_before_this_event(event)
250 | return _do_callback(self._callbacks["onbefore" .. event.name], event)
251 | end
252 |
253 | function simple_state_machine:_after_this_event(event)
254 | return _do_callback(self._callbacks["onafter" .. event.name] or self._callbacks["on" .. event.name], event)
255 | end
256 |
257 | function simple_state_machine:_leave_this_state(event)
258 | return _do_callback(self._callbacks["onleave" .. event.from], event)
259 | end
260 |
261 | function simple_state_machine:_enter_this_state(event)
262 | return _do_callback(self._callbacks["onenter" .. event.to] or self._callbacks["on" .. event.to], event)
263 | end
264 |
265 | function simple_state_machine:_before_event(event)
266 | if self:_before_this_event(event) == false or self:_before_any_event(event) == false then
267 | return false
268 | end
269 | end
270 |
271 | function simple_state_machine:_after_event(event)
272 | self:_after_this_event(event)
273 | self:_after_any_event(event)
274 | end
275 |
276 | function simple_state_machine:_leave_state(event, transition)
277 | local specific = self:_leave_this_state(event, transition)
278 | local general = self:_leave_any_state(event, transition)
279 | if specific == false or general == false then
280 | return false
281 | elseif string.upper(tostring(specific)) == simple_state_machine.ASYNC
282 | or string.upper(tostring(general)) == simple_state_machine.ASYNC then
283 | return simple_state_machine.ASYNC
284 | end
285 | end
286 |
287 | function simple_state_machine:_enter_state(event)
288 | self:_enter_this_state(event)
289 | self:_enter_any_state(event)
290 | end
291 |
292 | function simple_state_machine:_on_error(event, error, message)
293 | print("%s [simple_state_machine] ERROR: error %s, event %s, from %s to %s", tostring(self._target), tostring(error), event.name, event.from, event.to)
294 | print(message)
295 | end
296 |
297 | return simple_state_machine
--------------------------------------------------------------------------------
/BaseService/script/Framework/Stack.lua:
--------------------------------------------------------------------------------
1 | stack = { }
2 |
3 | function stack:create()
4 | local t = { }
5 | t._et = { }
6 |
7 | function t:push(...)
8 | if ... then
9 | local targs = { ...}
10 | for _, v in ipairs(targs) do
11 | table.insert(self._et, v)
12 | end
13 | end
14 | end
15 |
16 | function t:pop(num)
17 | local num = num or 1
18 | local entries = { }
19 | for i = 1, num do
20 | if #self._et ~= 0 then
21 | table.insert(entries, self._et[#self._et])
22 | table.remove(self._et)
23 | else
24 | break
25 | end
26 | end
27 | return unpack(entries)
28 | end
29 |
30 | function t:peek()
31 | if #self._et ~= 0 then
32 | return self._et[#self._et]
33 | end
34 | return nil
35 | end
36 |
37 | function t:clear()
38 | while #self._et ~= 0 do
39 | table.remove(self._et)
40 | end
41 | end
42 |
43 | function t:getn()
44 | return #self._et
45 | end
46 |
47 | function t:list()
48 | for i, v in pairs(self._et) do
49 | print(i, v)
50 | end
51 | end
52 |
53 | return t
54 | end
--------------------------------------------------------------------------------
/BaseService/script/Framework/StateFul.lua:
--------------------------------------------------------------------------------
1 | -- # Example
2 | -- ``` lua
3 | -- local class = require 'middleclass'
4 | -- local Stateful = require 'stateful'
5 | -- local Enemy = class('Enemy')
6 | -- Enemy:include(Stateful)
7 | -- function Enemy:initialize(health)
8 | -- self.health = health
9 | -- end
10 | -- function Enemy:speak()
11 | -- return 'My health is' .. tostring(self.health)
12 | -- end
13 | -- local Immortal = Enemy:addState('Immortal')
14 | -- -- overriden function
15 | -- function Immortal:speak()
16 | -- return 'I am UNBREAKABLE!!'
17 | -- end
18 | -- -- added function
19 | -- function Immortal:die()
20 | -- return 'I can not die now!'
21 | -- end
22 | -- local peter = Enemy:new(10)
23 | -- peter:speak() -- My health is 10
24 | -- peter:gotoState('Immortal')
25 | -- peter:speak() -- I am UNBREAKABLE!!
26 | -- peter:die() -- I can not die now!
27 | -- peter:gotoState(nil)
28 | -- peter:speak() -- My health is 10
29 | -- ```
30 | local Stateful = {static = {}}
31 |
32 | local _callbacks = {
33 | enteredState = 1,
34 | exitedState = 1,
35 | pushedState = 1,
36 | poppedState = 1,
37 | pausedState = 1,
38 | continuedState = 1
39 | }
40 |
41 | local _BaseState = {}
42 |
43 | local function _addStatesToClass(klass, superStates)
44 | klass.static.states = {}
45 | for stateName, state in pairs(superStates or {}) do
46 | klass:addState(stateName, state)
47 | end
48 | end
49 |
50 | local function _getStatefulMethod(instance, name)
51 | if not _callbacks[name] then
52 | local stack = rawget(instance, '__stateStack')
53 | if not stack then return end
54 | for i = #stack, 1, -1 do
55 | if stack[i][name] then return stack[i][name] end
56 | end
57 | end
58 | end
59 |
60 | local function _getNewInstanceIndex(prevIndex)
61 | if type(prevIndex) == 'function' then
62 | return function(instance, name) return _getStatefulMethod(instance, name) or prevIndex(instance, name) end
63 | end
64 | return function(instance, name) return _getStatefulMethod(instance, name) or prevIndex[name] end
65 | end
66 |
67 | local function _getNewAllocateMethod(oldAllocateMethod)
68 | return function(klass, ...)
69 | local instance = oldAllocateMethod(klass, ...)
70 | instance.__stateStack = {}
71 | return instance
72 | end
73 | end
74 |
75 | local function _modifyInstanceIndex(klass)
76 | klass.__instanceDict.__index = _getNewInstanceIndex(klass.__instanceDict.__index)
77 | end
78 |
79 | local function _getNewSubclassMethod(prevSubclass)
80 | return function(klass, name)
81 | local subclass = prevSubclass(klass, name)
82 | _addStatesToClass(subclass, klass.states)
83 | _modifyInstanceIndex(subclass)
84 | return subclass
85 | end
86 | end
87 |
88 | local function _modifySubclassMethod(klass)
89 | klass.static.subclass = _getNewSubclassMethod(klass.static.subclass)
90 | end
91 |
92 | local function _modifyAllocateMethod(klass)
93 | klass.static.allocate = _getNewAllocateMethod(klass.static.allocate)
94 | end
95 |
96 | local function _assertType(val, name, expected_type, type_to_s)
97 | assert(type(val) == expected_type, "Expected " .. name .. " to be of type " .. (type_to_s or expected_type) .. ". Was " .. tostring(val) .. "(" .. type(val) .. ")")
98 | end
99 |
100 | local function _assertInexistingState(klass, stateName)
101 | assert(klass.states[stateName] == nil, "State " .. tostring(stateName) .. " already exists on " .. tostring(klass))
102 | end
103 |
104 | local function _assertExistingState(self, state, stateName)
105 | assert(state, "The state " .. stateName .. " was not found in " .. tostring(self.class))
106 | end
107 |
108 | local function _invokeCallback(self, state, callbackName, ...)
109 | if state and state[callbackName] then state[callbackName](self, ...) end
110 | end
111 |
112 | local function _getCurrentState(self)
113 | return self.__stateStack[#self.__stateStack]
114 | end
115 |
116 | local function _getStateFromClassByName(self, stateName)
117 | local state = self.class.static.states[stateName]
118 | _assertExistingState(self, state, stateName)
119 | return state
120 | end
121 |
122 | local function _getStateIndexFromStackByName(self, stateName)
123 | if stateName == nil then return #self.__stateStack end
124 | local target = _getStateFromClassByName(self, stateName)
125 | for i = #self.__stateStack, 1, -1 do
126 | if self.__stateStack[i] == target then return i end
127 | end
128 | end
129 |
130 | local function _getStateName(self, target)
131 | for name, state in pairs(self.class.static.states) do
132 | if state == target then return name end
133 | end
134 | end
135 |
136 | function Stateful:included(klass)
137 | _addStatesToClass(klass)
138 | _modifyInstanceIndex(klass)
139 | _modifySubclassMethod(klass)
140 | _modifyAllocateMethod(klass)
141 | end
142 |
143 | function Stateful.static:addState(stateName, superState)
144 | superState = superState or _BaseState
145 | _assertType(stateName, 'stateName', 'string')
146 | _assertInexistingState(self, stateName)
147 | self.static.states[stateName] = setmetatable({}, {__index = superState})
148 | return self.static.states[stateName]
149 | end
150 |
151 | function Stateful:gotoState(stateName, ...)
152 |
153 | self:popAllStates()
154 |
155 | if stateName == nil then
156 | self.__stateStack = {}
157 | else
158 | _assertType(stateName, 'stateName', 'string', 'string or nil')
159 |
160 | local newState = _getStateFromClassByName(self, stateName)
161 | self.__stateStack = {newState}
162 | _invokeCallback(self, newState, 'enteredState', ...)
163 | end
164 |
165 | end
166 |
167 | function Stateful:pushState(stateName)
168 | local oldState = _getCurrentState(self)
169 | _invokeCallback(self, oldState, 'pausedState')
170 |
171 | local newState = _getStateFromClassByName(self, stateName)
172 | table.insert(self.__stateStack, newState)
173 |
174 | _invokeCallback(self, newState, 'pushedState')
175 | _invokeCallback(self, newState, 'enteredState')
176 | end
177 |
178 | function Stateful:popState(stateName)
179 |
180 | local oldStateIndex = _getStateIndexFromStackByName(self, stateName)
181 | local oldState
182 | if oldStateIndex then
183 | oldState = self.__stateStack[oldStateIndex]
184 |
185 | _invokeCallback(self, oldState, 'poppedState')
186 | _invokeCallback(self, oldState, 'exitedState')
187 |
188 | table.remove(self.__stateStack, oldStateIndex)
189 | end
190 |
191 | local newState = _getCurrentState(self)
192 |
193 | if oldState ~= newState then
194 | _invokeCallback(self, newState, 'continuedState')
195 | end
196 | end
197 |
198 | function Stateful:popAllStates()
199 | local size = #self.__stateStack
200 | for i = 1, size do self:popState() end
201 | end
202 |
203 | function Stateful:getStateStackDebugInfo()
204 | local info, state = {}, nil
205 | for i = #self.__stateStack, 1, -1 do
206 | state = self.__stateStack[i]
207 | table.insert(info, _getStateName(self, state))
208 | end
209 | return info
210 | end
211 |
212 | return Stateful
213 |
--------------------------------------------------------------------------------
/BaseService/script/Framework/Test/FSMClass.lua:
--------------------------------------------------------------------------------
1 | local FSMClass = class("FSMClass")
2 |
3 | -- 构造函数;
4 | function FSMClass:ctor()
5 |
6 | self._GameFSM = StateMachine:new();
7 |
8 | self._GameFSM:setup_state({
9 | events =
10 | {
11 | {name = "TChessStateWait" }, -- 等待游戏开始
12 | {name = "TChessStateStartGame" }, -- 开始游戏
13 | {name = "TChessStateAction" }, -- 玩家自由出牌状态
14 | {name = "TChessStateShowDown" }, -- 玩家结算状态
15 | {name = "TChessStateLeaveRoom" }, -- 离开
16 | },
17 | callbacks =
18 | {
19 | onTChessStateWait = handler(self, self.DoGameFSMWait),
20 | onTChessStateStartGame = handler(self, self.DoGameFSMStartGame),
21 | }
22 | })
23 | end
24 | function FSMClass:SwitchState( event, ... )
25 | if (self._GameFSM ~= nil) then
26 | self._GameFSM:do_event( event, ... );
27 | end
28 | end
29 |
30 | function FSMClass:DoGameFSMWait( event )
31 | print( "FSMClass:DoGameFSMWait" .. event.args[1] );
32 | end
33 |
34 | function FSMClass:DoGameFSMStartGame( event )
35 | print( "FSMClass:DoGameFSMStartGame".. event.args[1] );
36 | end
37 |
38 | return FSMClass;
--------------------------------------------------------------------------------
/BaseService/script/Framework/Test/TestFSM.lua:
--------------------------------------------------------------------------------
1 |
2 |
3 | local BasePath = "E:/BaseService/code/EVA/server/script/";
4 | package.path = BasePath .. "Framework/Test/?.lua;" .. BasePath .. "Framework/?.lua;";
5 |
6 | require("Class")
7 | require("functions")
8 |
9 | StateMachine = require("SimpleStateMachine");
10 |
11 |
12 |
13 | local FSMClass = require("FSMClass");
14 | fsm_class = FSMClass:new();
15 |
16 | fsm_class:SwitchState("TChessStateWait","=============");
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/BaseService/script/Framework/Test/TimerTest.lua:
--------------------------------------------------------------------------------
1 |
2 | local TimerTest = class("TimerTest")
3 |
4 | function TimerTest:ctor()
5 | self.val = 0;
6 |
7 | TimerMgr:AddTimer(1000, self, self.CallBack);
8 | end
9 |
10 | function TimerTest:CallBack()
11 |
12 |
13 |
14 |
15 | local timerid = TimerMgr:AddTimer(1000, self, self.CallBack);
16 |
17 | self.val = self.val+1;
18 | print("======"..self.val.." id:"..timerid);
19 |
20 | end
21 |
22 | --释放函数
23 | function TimerTest:Release()
24 |
25 | end
26 |
27 |
28 | return TimerTest;
29 |
--------------------------------------------------------------------------------
/BaseService/script/Framework/TimerMgr.lua:
--------------------------------------------------------------------------------
1 | utils = require("Utils")
2 |
3 | TimerMgr = {}
4 |
5 | function TimerMgr:Init(cycle)
6 |
7 | self.timerid = 1;
8 | self._removemap = {};
9 | self._cycle = cycle
10 | self._slots = {}
11 | self._slots[1] = {}
12 | self._slots[2] = {}
13 | self._slots[3] = {}
14 | self._slots[4] = {}
15 | utils.tinsert_n(self._slots[1], {}, 24)
16 | utils.tinsert_n(self._slots[2], {}, 60)
17 | utils.tinsert_n(self._slots[3], {}, 60)
18 | utils.tinsert_n(self._slots[4], {}, 1000)
19 | end
20 |
21 | function TimerMgr:Update(cycle)
22 | local h1, m1, s1, ms1 = utils.ms2t(self._cycle)
23 | self._cycle = cycle
24 | local h2, m2, s2, ms2 = utils.ms2t(self._cycle)
25 | self:__UpdateT__(24, 1, h1, h2, utils.bind(self.__UpdateH__, self))
26 | self:__UpdateT__(60, 2, m1, m2, utils.bind(self.__UpdateM__, self))
27 | self:__UpdateT__(60, 3, s1, s2, utils.bind(self.__UpdateS__, self))
28 | self:__UpdateT__(1000, 4, ms1, ms2, utils.bind(self.__UpdateMS__, self))
29 | end
30 |
31 | function TimerMgr:AddTimer(delay, obj, func)
32 | self.timerid = self.timerid + 1;
33 | self:__Insert__(delay + 1, self.timerid, utils.bind(func, obj) )
34 | return self.timerid;
35 | end
36 |
37 | function TimerMgr:RemoveTimer( timerid )
38 | if timerid~=nil then
39 | self._removemap[timerid]=true;
40 | end
41 | end
42 |
43 | function TimerMgr:__Insert__(delay, timerid, func)
44 | if 0 == delay then
45 | if self._removemap[timerid]==nil then
46 | func()
47 | else
48 | self._removemap[timerid] = nil;
49 | end
50 | else
51 | local h1, m1, s1, ms1 = utils.ms2t(delay)
52 | local h2, m2, s2, ms2 = utils.ms2t(delay + self._cycle)
53 | local tick = { func = func,
54 | id = timerid,
55 | time = { h = h2, m = m2, s = s2, ms = ms2 } }
56 | if h1 ~= 0 then
57 | table.insert(self._slots[1][h2 == 0 and 24 or h2], tick)
58 | elseif m1 ~= 0 then
59 | table.insert(self._slots[2][m2 == 0 and 60 or m2], tick)
60 | elseif s1 ~= 0 then
61 | table.insert(self._slots[3][s2 == 0 and 60 or s2], tick)
62 | elseif ms1 ~= 0 then
63 | table.insert(self._slots[4][ms2 == 0 and 1000 or ms2], tick)
64 | end
65 | end
66 | end
67 |
68 | function TimerMgr:__UpdateT__(cycle, index, first, last, func)
69 | local slots = self._slots[index]
70 | while first ~= last do
71 | first = first + 1
72 | for i = 1, #slots[first] do
73 | func(slots[first][i])
74 | end
75 | slots[first] = {}
76 | first = first % cycle
77 | end
78 | end
79 |
80 | function TimerMgr:__UpdateH__(v)
81 | self:__Insert__(utils.t2ms(0, v.time.m, v.time.s, v.time.ms), v.id, v.func)
82 | end
83 |
84 | function TimerMgr:__UpdateM__(v)
85 | self:__Insert__(utils.t2ms(0, 0, v.time.s, v.time.ms), v.id, v.func)
86 | end
87 |
88 | function TimerMgr:__UpdateS__(v)
89 | self:__Insert__(utils.t2ms(0, 0, 0, v.time.ms), v.id, v.func)
90 | end
91 |
92 | function TimerMgr:__UpdateMS__(v)
93 | self:__Insert__(utils.t2ms(0, 0, 0, 0), v.id, v.func)
94 | end
95 |
96 | return TimerMgr
97 |
--------------------------------------------------------------------------------
/BaseService/script/Framework/Utils.lua:
--------------------------------------------------------------------------------
1 | local _M = {}
2 |
3 | function _M.bind(func, ...)
4 | local args = {...}
5 | return function(...)
6 | func(table.unpack(args), ...)
7 | end
8 | end
9 |
10 | function _M.dump(value, dep)
11 | dep = dep or ""
12 | local ret = ""
13 | if type(value) == "table" then
14 | ret = ret .. "{\n"
15 | for k, v in pairs(value) do
16 | ret = string.format("%s%s\t[%s] = %s\n", ret, dep, k, dump(v, dep .. "\t"))
17 | end
18 | ret = ret .. dep .. "},\n"
19 | else
20 | ret = ret .. tostring(value) .. ", "
21 | end
22 | return ret
23 | end
24 |
25 | function _M.clone(src)
26 | local ret = {}
27 | if type(src) == "table" then
28 | for k, v in pairs(src) do
29 | ret[k] = _M.clone(v)
30 | end
31 | else
32 | ret = src
33 | end
34 | return ret
35 | end
36 |
37 | function _M.tinsert_n(src, val, n)
38 | for i = 1, n do
39 | table.insert(src, _M.clone(val))
40 | end
41 | end
42 |
43 | function _M.ms2t(cycle)
44 | local s = math.floor(cycle / 1000)
45 | local m = math.floor(cycle / 60000)
46 | local h = math.floor(cycle / 3600000)
47 | local ms = cycle - h * 3600000 - m * 60000 - s * 1000
48 | return math.floor(h % 24), math.floor(m % 60), math.floor(s % 60), math.floor(ms % 1000)
49 | end
50 |
51 | function _M.t2ms(h, m, s, ms)
52 | return h * 3600000 + m * 60000 + s * 1000 + ms
53 | end
54 |
55 | return _M
--------------------------------------------------------------------------------
/BaseService/script/Framework/functions.lua:
--------------------------------------------------------------------------------
1 |
2 |
3 | --[[
4 | 实际上,除了 C++ 回调 Lua 函数之外,在其他所有需要回调的地方都可以使用 handler()。
5 |
6 | @param mixed obj Lua 对象
7 | @param function method 对象方法
8 |
9 | @return function
10 |
11 | ]]--
12 |
13 | function handler(obj, method)
14 | if (nil == obj or nil == method) then
15 | logError("handler param == nil");
16 | return nil;
17 | end
18 | return function(...)
19 | return method(obj, ...)
20 | end
21 | end
22 |
23 | function checktable(value)
24 | if type(value) ~= "table" then value = {} end
25 | return value
26 | end
27 |
28 | function md5(value)
29 | return Misc.MD5( value, string.len(value) );
30 | end
31 |
32 | function nldebug( str )
33 | Debug.Debug(str,2);
34 | end
35 |
36 | function nlinfo( str )
37 | Debug.Info(str,2);
38 | end
39 |
40 | function nlwarning( str )
41 | Debug.Warning(str,2);
42 | end
43 |
44 | function nlstop( str )
45 | Debug.Stop(str,2);
46 | end
47 |
48 | print = nlinfo;
49 |
50 | function enum(enum_type, enum_name)
51 | return protobuf.enum_id(enum_type, enum_name);
52 | end
53 |
54 |
55 | function shuffle(tbl)
56 |
57 | local tbl_count = #tbl;
58 | for i=1,tbl_count do
59 | local ridx = math.random(1, tbl_count);
60 | if i~=ridx then
61 | local temp = tbl[i];
62 | tbl[i] = tbl[ridx];
63 | tbl[ridx] = temp;
64 | end
65 | end
66 | end
67 |
68 | function SetBit( val, enum_type, enum_name )
69 | local enum_val = protobuf.enum_id(enum_type, enum_name);
70 | Misc.SetBit(val, enum_val);
71 | return val;
72 | end
73 |
74 | function GetServiceID()
75 | return ServerNet.GetServiceID();
76 | end
77 |
78 | function PostSub( thread_name, event_type, pb_name, pb_data, from )
79 |
80 | code = protobuf.encode(pb_name, pb_data)
81 | len = string.len(code);
82 |
83 | msg = { thread_name, from, event_type, len };
84 | LuaThread.PostSub(code, msg);
85 |
86 | end
87 |
88 | function PostMain( thread_name, event_type, pb_name, pb_data, from )
89 |
90 | code = protobuf.encode(pb_name, pb_data)
91 | len = string.len(code);
92 |
93 | msg = { thread_name, from, event_type, len };
94 | LuaThread.PostMain(code, msg);
95 |
96 | end
97 |
98 | function PrintTable( tbl, indent, depth )
99 | Debug.Info(JsonUtil.serialise_value(tbl, indent, depth), 2);
100 | --[[
101 | if tbl==nil then
102 | return;
103 | end
104 |
105 | local msg = ""
106 | depth = depth or 1
107 | local indent_str = ""
108 |
109 | for i = 2, depth do
110 | indent_str = indent_str.." "
111 | end
112 |
113 | print(indent_str .. "{")
114 | for k,v in pairs(tbl) do
115 | if k ~= "class" then
116 | local item_str = string.format("%s%s = %s", indent_str .. " ",tostring(k), tostring(v))
117 | print(item_str)
118 |
119 | if type(v) == "table" then
120 | PrintTable(v, depth + 1)
121 | end
122 | end
123 | end
124 | print(indent_str .. "}")
125 |
126 | --]]
127 | end
128 |
129 | function Table2Json( tbl )
130 | return JsonUtil.serialise_value(tbl);
131 | end
132 |
133 | function Json2Table( str )
134 | return Json.decode(str);
135 | end
136 |
137 | function PB2Table( pb_stru, pb_data )
138 | return protobuf.decode(pb_stru, pb_data);
139 | end
140 |
141 | -- start --
142 |
143 | --------------------------------
144 | -- 从表格中删除指定值,返回删除的值的个数
145 | -- @function [parent=#table] removebyvalue
146 | -- @param table array 表格
147 | -- @param mixed value 要删除的值
148 | -- @param boolean removeall 是否删除所有相同的值
149 | -- @return integer#integer
150 |
151 | --[[--
152 |
153 | 从表格中删除指定值,返回删除的值的个数
154 |
155 | ~~~ lua
156 |
157 | local array = {"a", "b", "c", "c"}
158 | print(table.removebyvalue(array, "c", true)) -- 输出 2
159 |
160 | ~~~
161 |
162 | ]]
163 |
164 | -- end --
165 | function table.removebyvalue(array, value, removeall)
166 | local c, i, max = 0, 1, #array
167 | while i <= max do
168 | if array[i] == value then
169 | table.remove(array, i)
170 | c = c + 1
171 | i = i - 1
172 | max = max - 1
173 | if not removeall then break end
174 | end
175 | i = i + 1
176 | end
177 | return c
178 | end
179 |
180 | function get_data_by_sec(sec)
181 | sec = sec < 0 and 0 or sec
182 | local data =
183 | {
184 | day = math.floor(sec / 3600 / 24),
185 | hour = math.floor(sec / 3600) % 24,
186 | min = math.floor(sec % 3600 / 60),
187 | sec = sec % 60,
188 | }
189 | return data
190 | end
191 |
192 | -- 单例模式
193 | function singleton(classname, super)
194 | local cls = {}
195 | if super then
196 | for k,v in pairs(super) do cls[k] = v end
197 | cls.super = super
198 | else
199 | cls.ctor = function() end
200 | end
201 |
202 | cls.__cname = classname
203 | cls.__index = cls
204 |
205 | local Instance = setmetatable({class = cls}, cls)
206 | function cls.Instance()
207 | return Instance
208 | end
209 | return cls
210 | end
211 |
212 | -- 分割字符串
213 | function SplitStr(str, reps)
214 | local resultStrList = {}
215 | string.gsub(str,'[^'..reps..']+',function ( w )
216 | table.insert(resultStrList,w)
217 | end)
218 | return resultStrList
219 | end
220 |
221 | -- 获取随机数
222 | function GetRandom(min, max)
223 | math.randomseed(tostring(os.time()):reverse():sub(1, 7))
224 | return math.random(min, max);
225 | end
226 |
227 | -- 字符串加密
228 | function urlEncode(s)
229 | s = string.gsub(s, "([^%w%.%- ])", function(c) return string.format("%%%02X", string.byte(c)) end)
230 | return string.gsub(s, " ", "+")
231 | end
232 |
233 | -- 解密
234 | function urlDecode(s)
235 | s = string.gsub(s, '%%(%x%x)', function(h) return string.char(tonumber(h, 16)) end)
236 | return s
237 | end
238 |
239 | -- 检查表中是否存在
240 | function IsInTable(value, tbl)
241 | if nil == tbl then return false; end
242 | for k,v in pairs(tbl) do
243 | if v == value then
244 | return true;
245 | end
246 | end
247 | return false;
248 | end
249 |
250 | function ReverseTable(tab)
251 | local tmp = {}
252 | for i = 1, #tab do
253 | local key = #tab
254 | tmp[i] = table.remove(tab)
255 | end
256 |
257 | return tmp
258 | end
--------------------------------------------------------------------------------
/BaseService/script/SharedLib/Event/EventType.lua:
--------------------------------------------------------------------------------
1 | --=========================================================
2 | -- 事件类型
3 | --=========================================================
4 |
5 | EventType =
6 | {
7 | -- 内部事件 格式:[EVENT_XXXXX]
8 | EVENT_LOGIN = "EVENT_LOGIN"; -- 执行登录状态切换
9 |
10 | }
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/BaseService/script/SharedLib/InitSharedLib.lua:
--------------------------------------------------------------------------------
1 | --=========================================================
2 | -- 初始化游戏内共享工具,游戏逻辑相关。
3 | --=========================================================
4 |
5 | local BasePath = Misc.GetBasePath() .. "/script/";
6 | package.path = package.path .. BasePath .. "Framework/?.lua;";
7 |
8 | require("InitFramework")
9 |
10 |
11 | require("StaticTableMgr");
12 | require("Event/EventType");
13 |
14 |
15 |
16 |
17 |
18 | -- 初始化单例
19 | function OnInitSharedLib()
20 |
21 | StaticTableMgr:Init();
22 |
23 | end
24 |
25 |
26 |
27 | OnInitSharedLib();
28 |
29 |
30 |
--------------------------------------------------------------------------------
/BaseService/script/SharedLib/StaticTableMgr.lua:
--------------------------------------------------------------------------------
1 | StaticTableMgr = {}
2 |
3 | function StaticTableMgr:Init()
4 |
5 | local ConfigPath = Misc.GetBasePath() .. "/script/DataTable/";
6 |
7 | local json_text = JsonUtil.file_load(ConfigPath.."RoomConfig.json")
8 | self._RoomConfig = Json.decode(json_text)
9 |
10 |
11 | end
12 |
13 |
14 | function StaticTableMgr:GetRoomConfigXml( room_type )
15 | return self._RoomConfig[tostring(room_type)];
16 | end
17 |
18 |
19 | return StaticTableMgr;
20 |
21 |
--------------------------------------------------------------------------------
/BaseService/script/_FES.luaprj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/BaseService/script/_FES/Client/Client.lua:
--------------------------------------------------------------------------------
1 | local Client = class("Client")
2 |
3 | -- 构造函数;
4 | function Client:ctor()
5 | self.SockID = nil;
6 | self.ConPLS = nil;
7 | self.UID = nil;
8 | end
9 |
10 |
11 | return Client;
12 |
--------------------------------------------------------------------------------
/BaseService/script/_FES/Client/ClientMgr.lua:
--------------------------------------------------------------------------------
1 | ClientMgr = {}
2 |
3 | -- 初始化函数
4 | function ClientMgr:Init()
5 | self.ClientMap = {};
6 | self.SocketMap = {};
7 | end
8 |
9 | function ClientMgr:GetClient( _uid )
10 | if self.ClientMap[_uid] ~= nil then
11 | return self.ClientMap[_uid];
12 | end
13 | return nil;
14 | end
15 |
16 | function ClientMgr:SetClient( _uid, _client )
17 |
18 | if _uid ~= _client.UID then assert() end;
19 |
20 | if self.ClientMap[_uid] == nil then
21 | self.ClientMap[_uid] = _client;
22 | self.SocketMap[_client.SockID] = self.ClientMap[_uid];
23 | else
24 | local old_client = self.ClientMap[_client.UID];
25 | self.SocketMap[old_client.SockID] = nil;
26 |
27 | self.ClientMap[_uid] = _client;
28 | self.SocketMap[_client.SockID] = self.ClientMap[_uid];
29 | end
30 | end
31 |
32 | function ClientMgr:RemoveClient( _uid )
33 | if self.ClientMap[_uid] ~= nil then
34 | local old_client = self.ClientMap[_uid];
35 | self.SocketMap[old_client.SockID] = nil;
36 | self.ClientMap[_uid] = nil;
37 |
38 | ClientService:RemoveClientData(_uid);
39 | end
40 | end
41 |
42 | function ClientMgr:RemoveSockID( _sockid )
43 | if self.SocketMap[_sockid] ~= nil then
44 | local old_client = self.SocketMap[_sockid];
45 |
46 | print("ClientMgr:RemoveSockID:".._sockid.." UID:"..old_client.UID);
47 |
48 | ClientService:RemoveClientData(old_client.UID);
49 | self.ClientMap[old_client.UID] = nil;
50 | self.SocketMap[_sockid] = nil;
51 | end
52 | end
53 |
54 | return ClientMgr
55 |
--------------------------------------------------------------------------------
/BaseService/script/_FES/FrontEndService.lua:
--------------------------------------------------------------------------------
1 | FrontEndService = {}
2 |
3 | function FrontEndService:Init()
4 | self._EventRegister = EventRegister.new();
5 |
6 | self._EventRegister:RegisterEvent( "FESCon", self, self.Connection );
7 | self._EventRegister:RegisterEvent( "FESDis", self, self.DisConnection );
8 | self._EventRegister:RegisterEvent( "PLSCon", self, self.Connection );
9 | self._EventRegister:RegisterEvent( "PLSDis", self, self.DisConnection );
10 |
11 | -- 注册其它服务器启动的回调
12 | ServerNet.SetConnectionCallback("FES");
13 | ServerNet.SetDisConnectionCallback("FES");
14 |
15 | ServerNet.SetConnectionCallback("PLS");
16 | ServerNet.SetDisConnectionCallback("PLS");
17 |
18 | end
19 |
20 |
21 | function FrontEndService:Connection( service_id, service_name )
22 | print("FrontEndService:Connection:"..service_name.." sid:"..service_id);
23 | end
24 |
25 | function FrontEndService:DisConnection( service_id, service_name )
26 | print("FrontEndService:DisConnection"..service_name.." sid:"..service_id);
27 | end
28 |
29 | -- 释放函数
30 | function FrontEndService:Release()
31 | self._EventRegister:UnRegisterAllEvent();
32 | end
33 |
34 | return FrontEndService
35 |
36 |
--------------------------------------------------------------------------------
/BaseService/script/_FES/Msg/MsgLogin.lua:
--------------------------------------------------------------------------------
1 | local MsgLogin = class("MsgLogin")
2 |
3 | -- 构造函数;
4 | function MsgLogin:ctor( Data )
5 |
6 | self._EventRegister = EventRegister.new();
7 |
8 | self._EventRegister:RegisterEvent( ClientService.ConnectCallbackEvent, self, self.Connect );
9 | self._EventRegister:RegisterEvent( ClientService.DisConnectCallbackEvent, self, self.DisConnect );
10 |
11 | -- 客户端消息
12 | self._EventRegister:RegisterEvent( "LOGIN", self, self.CBLogin );
13 |
14 | -- 服务器间消息
15 | self._EventRegister:RegisterEvent( "AuthOk", self, self.CBAuthOk ); -- 有客户端在其它FES上登录成功。RemoveClient
16 | self._EventRegister:RegisterEvent( "SyncData", self, self.CBLoginPLS ); -- 在PLS上登录成功。
17 |
18 |
19 | end
20 |
21 | function MsgLogin:CBLogin( sock_id, msg_login )
22 |
23 | local tbl_login = msg_login:rpb("PB.MsgLogin");
24 | PrintTable(tbl_login);
25 |
26 | -- 验证签名
27 | local sign_str = tbl_login.UID .. tbl_login.Channel .. tbl_login.RoomType .. tbl_login.AppName;
28 | sign_str = sign_str .. tbl_login.User .. tbl_login.NonceStr .. tbl_login.Timestamp;
29 | sign_str = sign_str .. "BLACKSHEEPWALL";
30 |
31 | local sign = string.upper( md5(sign_str) );
32 |
33 |
34 | print("sign_str:"..sign_str);
35 | print("sign:"..sign);
36 |
37 |
38 |
39 | -------------- 账号认证通过
40 | local msg_authok = CMessage("AuthOk");
41 | msg_authok:wint64(tbl_login.UID);
42 | BaseService:Broadcast( "FES", msg_authok ) -- 通知其它网关有玩家登录成功。
43 |
44 | msg_authok:wstring(tbl_login.RoomType);
45 | BaseService:Broadcast( "SCH", msg_authok ) -- 玩家认证通过,请求发送数据。
46 |
47 | -- 保存客户端连接
48 | local client = ClientMgr:GetClient(tbl_login.UID);
49 |
50 | if( client ~= nil ) then
51 | client.SockID = sock_id;
52 | else
53 | client = Client:new();
54 | client.SockID = sock_id;
55 | client.UID = tbl_login.UID;
56 |
57 | ClientMgr:SetClient(tbl_login.UID, client);
58 | end
59 |
60 | -- 通知客户端 账号认证通过.
61 | ClientService:Send( sock_id, "AuthOk" );
62 |
63 | end
64 |
65 | -- 有客户端在其它FES上登录成功。RemoveClient
66 | function MsgLogin:CBAuthOk( sock_id, msg_authok )
67 |
68 | local uid = msg_authok:rint64();
69 | print("MsgLogin:AuthOk"..uid);
70 | ClientMgr:RemoveClient(uid);
71 |
72 | end
73 |
74 | function MsgLogin:CBLoginPLS( pls_id, msg_sdata_2 )
75 |
76 | local uid = msg_sdata_2:rint64();
77 | local client = ClientMgr:GetClient(uid);
78 |
79 | if( client ~= nil ) then
80 | client.ConPLS = pls_id;
81 |
82 | -- 设置UID相关信息,用于底层转发消息。 msg.xml
83 | ClientService:SetClientData( {client.UID, client.SockID, pls_id} );
84 | end
85 | end
86 |
87 |
88 | function MsgLogin:Connect( sock_id )
89 | print("CallbackClient:Connect"..sock_id);
90 | end
91 |
92 | function MsgLogin:DisConnect( sock_id )
93 | print("CallbackClient:DisConnect"..sock_id);
94 | ClientMgr:RemoveSockID(sock_id);
95 | end
96 |
97 |
98 | --释放函数
99 | function MsgLogin:Release()
100 | self._EventRegister:UnRegisterAllEvent();
101 | end
102 |
103 |
104 | return MsgLogin;
105 |
--------------------------------------------------------------------------------
/BaseService/script/_FES/Player/PlayerInfo.lua:
--------------------------------------------------------------------------------
1 | -- Player PLS Info
2 | local PlayerInfo = class("PlayerInfo")
3 |
4 | -- 构造函数;
5 | function PlayerInfo:ctor()
6 | self.PLSID = nil;
7 | self.UID = nil;
8 | end
9 |
10 | return PlayerInfo;
11 |
--------------------------------------------------------------------------------
/BaseService/script/_FES/Player/PlayerInfoMgr.lua:
--------------------------------------------------------------------------------
1 | PlayerInfoMgr = {}
2 |
3 | -- 初始化函数
4 | function PlayerInfoMgr:Init()
5 | self.PlayerInfoMap = Map:new();
6 | end
7 |
8 | function PlayerInfoMgr:GetPlayerInfo( _uid )
9 | return self.PlayerInfoMap:Find(_uid);
10 | end
11 |
12 | function PlayerInfoMgr:SetPlayerInfo( _uid, _playerinfo )
13 | if _uid ~= _playerinfo.UID then assert() end;
14 |
15 | self.PlayerInfoMap:Insert(_uid, _playerinfo);
16 | end
17 |
18 | function PlayerInfoMgr:RemovePlayerInfo( _uid )
19 | self.PlayerInfoMap:Remove(_uid);
20 | end
21 |
22 | function PlayerInfoMgr:RemovePLS( pls_sid )
23 | self.PlayerInfoMap:ForEachRemove("PLSID", pls_sid);
24 | end
25 |
26 | return PlayerInfoMgr
27 |
--------------------------------------------------------------------------------
/BaseService/script/_FES/_FESMain.lua:
--------------------------------------------------------------------------------
1 | --=========================================================
2 | -- 加载常用模块
3 | --=========================================================
4 |
5 | local BasePath = Misc.GetBasePath() .. "/script/";
6 | package.path = BasePath .. "_FES/?.lua;" .. BasePath .. "SharedLib/?.lua;";
7 |
8 | require("InitSharedLib")
9 | require("FrontEndService");
10 | require("Client/ClientMgr");
11 |
12 |
13 | -- Class
14 | Client = require("Client/Client");
15 | MsgLogin = require("Msg/MsgLogin");
16 |
17 |
18 | ClientService = CallbackServer:new();
19 | LoginModule = MsgLogin:new();
20 |
21 |
22 |
23 | -- 主入口函数。从这里开始lua逻辑
24 | function ServiceInit()
25 |
26 | print(" =========FES Main Start============ ");
27 |
28 | ClientMgr:Init();
29 | FrontEndService:Init();
30 |
31 | ClientService:Init( "ClientService", "ws" );
32 |
33 | --ClientService:LoadSslCA(BasePath.."DataTable/ssl/1_root_bundle.crt");
34 | --ClientService:LoadSslCrt(BasePath.."DataTable/ssl/2_ssl.com.crt");
35 | --ClientService:LoadSslPrivateKey(BasePath.."DataTable/ssl/3_ssl.com.key");
36 |
37 | ClientService:Listen( 9999 );
38 |
39 | end
40 |
41 | -- 游戏循环
42 | function ServiceUpdate()
43 | TimerMgr:Update(math.floor(os.clock() * 1000))
44 | end
45 |
46 | function ServiceRelease()
47 | print("Lua Release.");
48 | end
49 |
50 | --[[
51 |
52 | --bash_path = "E:\\BaseService\\code\\EVA\\server\\script\\";
53 | --package.path = bash_path .. "Framework\\?.lua;" .. bash_path .. "Framework\\Net\\?.lua;";
54 |
55 | print(package.path);
56 |
57 | local protobuf = require "protobuf"
58 |
59 | addr = io.open( bash_path.."DataTable\\proto_msg.pb", "rb")
60 | buffer = addr:read "*a"
61 | addr:close()
62 |
63 | protobuf.register(buffer)
64 |
65 | t = protobuf.decode("google.protobuf.FileDescriptorSet", buffer)
66 |
67 | player_info = {
68 | name = "Alice",
69 | pid = 12345,
70 | view_player_list = {
71 | { pid = 17712345678, head_portrait = 1 },
72 | { pid = 17712345679, head_portrait = 2 },
73 | },
74 | level = 2
75 | }
76 |
77 |
78 | code = protobuf.encode("MsgPlayerInfo", player_info)
79 | decode = protobuf.decode("MsgPlayerInfo" , code)
80 |
81 | print(decode.name)
82 | print(decode.pid)
83 |
84 | for _,v in ipairs(decode.view_player_list) do
85 | print("\t"..v.pid, v.head_portrait)
86 | end
87 |
88 | ]]
--------------------------------------------------------------------------------
/BaseService/vccorlib110.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li9chuan/EgretWebSocket/d72c82d6c26d77851c705444e7c9f0143fc249d8/BaseService/vccorlib110.dll
--------------------------------------------------------------------------------
/EgretWebSocket/.wing/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | "name": "Launch Wing Player",
6 | "type": "chrome",
7 | "request": "launch",
8 | "file": "index.html",
9 | "runtimeExecutable": "${execPath}",
10 | "useBuildInServer": true,
11 | "sourceMaps": true,
12 | "webRoot": "${workspaceRoot}",
13 | "preLaunchTask":"build",
14 | "port":5840
15 | },
16 | {
17 | "name": "Launch Chrome",
18 | "type": "chrome",
19 | "request": "launch",
20 | "file": "index.html",
21 | "useBuildInServer": true,
22 | "sourceMaps": true,
23 | "webRoot": "${workspaceRoot}",
24 | "preLaunchTask":"build",
25 | "userDataDir":"${tmpdir}",
26 | "port":5840
27 | }
28 | ]
29 | }
--------------------------------------------------------------------------------
/EgretWebSocket/.wing/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "search.exclude": {
3 | "**/bin-debug": true,
4 | "**/bin-release": true
5 | }
6 | }
--------------------------------------------------------------------------------
/EgretWebSocket/.wing/tasks.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.1.0",
3 | "command": "egret",
4 | "isShellCommand": true,
5 | "suppressTaskName": true,
6 | "tasks": [
7 | {
8 | "taskName": "build",
9 | "showOutput": "always",
10 | "args": [
11 | "build",
12 | "-sourcemap"
13 | ],
14 | "problemMatcher": "$tsc"
15 | },
16 | {
17 | "taskName": "clean",
18 | "showOutput": "always",
19 | "args": [
20 | "build",
21 | "-e"
22 | ],
23 | "problemMatcher": "$tsc"
24 | },
25 | {
26 | "taskName": "publish",
27 | "showOutput": "always",
28 | "args": [
29 | "publish"
30 | ],
31 | "problemMatcher": "$tsc"
32 | }
33 | ]
34 | }
--------------------------------------------------------------------------------
/EgretWebSocket/bin-debug/LoadingUI.js:
--------------------------------------------------------------------------------
1 | //////////////////////////////////////////////////////////////////////////////////////
2 | //
3 | // Copyright (c) 2014-present, Egret Technology.
4 | // All rights reserved.
5 | // Redistribution and use in source and binary forms, with or without
6 | // modification, are permitted provided that the following conditions are met:
7 | //
8 | // * Redistributions of source code must retain the above copyright
9 | // notice, this list of conditions and the following disclaimer.
10 | // * Redistributions in binary form must reproduce the above copyright
11 | // notice, this list of conditions and the following disclaimer in the
12 | // documentation and/or other materials provided with the distribution.
13 | // * Neither the name of the Egret nor the
14 | // names of its contributors may be used to endorse or promote products
15 | // derived from this software without specific prior written permission.
16 | //
17 | // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
18 | // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 | // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 | // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
21 | // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
23 | // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
24 | // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25 | // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
26 | // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 | //
28 | //////////////////////////////////////////////////////////////////////////////////////
29 | var __reflect = (this && this.__reflect) || function (p, c, t) {
30 | p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t;
31 | };
32 | var __extends = this && this.__extends || function __extends(t, e) {
33 | function r() {
34 | this.constructor = t;
35 | }
36 | for (var i in e) e.hasOwnProperty(i) && (t[i] = e[i]);
37 | r.prototype = e.prototype, t.prototype = new r();
38 | };
39 | var LoadingUI = (function (_super) {
40 | __extends(LoadingUI, _super);
41 | function LoadingUI() {
42 | var _this = _super.call(this) || this;
43 | _this.createView();
44 | return _this;
45 | }
46 | LoadingUI.prototype.createView = function () {
47 | this.textField = new egret.TextField();
48 | this.addChild(this.textField);
49 | this.textField.y = 300;
50 | this.textField.width = 480;
51 | this.textField.height = 100;
52 | this.textField.textAlign = "center";
53 | };
54 | LoadingUI.prototype.onProgress = function (current, total) {
55 | this.textField.text = "Loading..." + current + "/" + total;
56 | };
57 | return LoadingUI;
58 | }(egret.Sprite));
59 | __reflect(LoadingUI.prototype, "LoadingUI", ["RES.PromiseTaskReporter"]);
60 | //# sourceMappingURL=LoadingUI.js.map
--------------------------------------------------------------------------------
/EgretWebSocket/bin-debug/LoadingUI.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"file":"LoadingUI.js","sourceRoot":"","sources":["../src/LoadingUI.ts"],"names":[],"mappings":"AAAA,sFAAsF;AACtF,EAAE;AACF,iDAAiD;AACjD,wBAAwB;AACxB,sEAAsE;AACtE,+EAA+E;AAC/E,EAAE;AACF,uEAAuE;AACvE,sEAAsE;AACtE,0EAA0E;AAC1E,4EAA4E;AAC5E,6EAA6E;AAC7E,8CAA8C;AAC9C,6EAA6E;AAC7E,8EAA8E;AAC9E,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,2EAA2E;AAC3E,gFAAgF;AAChF,gFAAgF;AAChF,8EAA8E;AAC9E,6EAA6E;AAC7E,wEAAwE;AACxE,gFAAgF;AAChF,sDAAsD;AACtD,EAAE;AACF,sFAAsF;;;;;;;;;;;AAEtF;IAAwB,6BAAY;IAEhC;QAAA,YACI,iBAAO,SAEV;QADG,KAAI,CAAC,UAAU,EAAE,CAAC;;IACtB,CAAC;IAIO,8BAAU,GAAlB;QACI,IAAI,CAAC,SAAS,GAAG,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;QACvC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAC9B,IAAI,CAAC,SAAS,CAAC,CAAC,GAAG,GAAG,CAAC;QACvB,IAAI,CAAC,SAAS,CAAC,KAAK,GAAG,GAAG,CAAC;QAC3B,IAAI,CAAC,SAAS,CAAC,MAAM,GAAG,GAAG,CAAC;QAC5B,IAAI,CAAC,SAAS,CAAC,SAAS,GAAG,QAAQ,CAAC;IACxC,CAAC;IAEM,8BAAU,GAAjB,UAAkB,OAAe,EAAE,KAAa;QAC5C,IAAI,CAAC,SAAS,CAAC,IAAI,GAAG,eAAa,OAAO,SAAI,KAAO,CAAC;IAC1D,CAAC;IACL,gBAAC;AAAD,CAAC,AArBD,CAAwB,KAAK,CAAC,MAAM,GAqBnC;AArBK,UAAA,SAAS,qDAqBd,CAAA"}
--------------------------------------------------------------------------------
/EgretWebSocket/bin-debug/Main.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"file":"Main.js","sourceRoot":"","sources":["../src/Main.ts"],"names":[],"mappings":"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"}
--------------------------------------------------------------------------------
/EgretWebSocket/bin-debug/Platform.js:
--------------------------------------------------------------------------------
1 | var __reflect = (this && this.__reflect) || function (p, c, t) {
2 | p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t;
3 | };
4 | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
5 | return new (P || (P = Promise))(function (resolve, reject) {
6 | function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
7 | function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
8 | function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
9 | step((generator = generator.apply(thisArg, _arguments || [])).next());
10 | });
11 | };
12 | var __generator = (this && this.__generator) || function (thisArg, body) {
13 | var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
14 | return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
15 | function verb(n) { return function (v) { return step([n, v]); }; }
16 | function step(op) {
17 | if (f) throw new TypeError("Generator is already executing.");
18 | while (_) try {
19 | if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
20 | if (y = 0, t) op = [0, t.value];
21 | switch (op[0]) {
22 | case 0: case 1: t = op; break;
23 | case 4: _.label++; return { value: op[1], done: false };
24 | case 5: _.label++; y = op[1]; op = [0]; continue;
25 | case 7: op = _.ops.pop(); _.trys.pop(); continue;
26 | default:
27 | if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
28 | if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
29 | if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
30 | if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
31 | if (t[2]) _.ops.pop();
32 | _.trys.pop(); continue;
33 | }
34 | op = body.call(thisArg, _);
35 | } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
36 | if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
37 | }
38 | };
39 | var DebugPlatform = (function () {
40 | function DebugPlatform() {
41 | }
42 | DebugPlatform.prototype.getUserInfo = function () {
43 | return __awaiter(this, void 0, void 0, function () {
44 | return __generator(this, function (_a) {
45 | return [2 /*return*/, { nickName: "username" }];
46 | });
47 | });
48 | };
49 | DebugPlatform.prototype.login = function () {
50 | return __awaiter(this, void 0, void 0, function () {
51 | var user;
52 | return __generator(this, function (_a) {
53 | user = ClientModule.GetInstance().UserInfo;
54 | user.NonceStr = "6GosND6R6HCeDWFPGWjQ";
55 | user.Token = "C5F9DB80F40EC9A98EA0E94604091198";
56 | user.UID = 1002;
57 | user.FES = "ws://127.0.0.1:9999";
58 | user.Timestamp = 1523541253;
59 | user.User = "oYsC35RNsWxsYQkKGsZVhxEImRuw";
60 | ClientModule.GetInstance().Version = "1.0";
61 | ClientModule.GetInstance().Channel = "WX";
62 | ClientModule.GetInstance().AppName = "WX_5E8A";
63 | ClientModule.GetInstance().RoomType = "RM_DDZ";
64 | ClientModule.GetInstance().User = "oYsC35RNsWxsYQkKGsZVhxEImRuw";
65 | NetMgr.GetInstance().Connect(user.FES);
66 | return [2 /*return*/];
67 | });
68 | });
69 | };
70 | return DebugPlatform;
71 | }());
72 | __reflect(DebugPlatform.prototype, "DebugPlatform", ["Platform"]);
73 | if (!window.platform) {
74 | window.platform = new DebugPlatform();
75 | }
76 | //# sourceMappingURL=Platform.js.map
--------------------------------------------------------------------------------
/EgretWebSocket/bin-debug/Platform.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"file":"Platform.js","sourceRoot":"","sources":["../src/Platform.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA;IAAA;IAuBA,CAAC;IAtBS,mCAAW,GAAjB;;;gBACI,sBAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,EAAA;;;KAClC;IACK,6BAAK,GAAX;;;;gBAEQ,IAAI,GAAa,YAAY,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC;gBAEzD,IAAI,CAAC,QAAQ,GAAK,sBAAsB,CAAC;gBACzC,IAAI,CAAC,KAAK,GAAQ,kCAAkC,CAAC;gBACrD,IAAI,CAAC,GAAG,GAAU,IAAI,CAAC;gBACvB,IAAI,CAAC,GAAG,GAAU,qBAAqB,CAAC;gBACxC,IAAI,CAAC,SAAS,GAAI,UAAU,CAAC;gBAC7B,IAAI,CAAC,IAAI,GAAS,8BAA8B,CAAC;gBAEjD,YAAY,CAAC,WAAW,EAAE,CAAC,OAAO,GAAI,KAAK,CAAC;gBAC5C,YAAY,CAAC,WAAW,EAAE,CAAC,OAAO,GAAI,IAAI,CAAC;gBAC3C,YAAY,CAAC,WAAW,EAAE,CAAC,OAAO,GAAI,SAAS,CAAC;gBAChD,YAAY,CAAC,WAAW,EAAE,CAAC,QAAQ,GAAG,QAAQ,CAAC;gBAC/C,YAAY,CAAC,WAAW,EAAE,CAAC,IAAI,GAAO,8BAA8B,CAAC;gBAErE,MAAM,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;;;;KAC1C;IACL,oBAAC;AAAD,CAAC,AAvBD,IAuBC;AAvBK,UAAA,aAAa,0CAuBlB,CAAA;AAGD,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC;IACnB,MAAM,CAAC,QAAQ,GAAG,IAAI,aAAa,EAAE,CAAC;AAC1C,CAAC"}
--------------------------------------------------------------------------------
/EgretWebSocket/bin-debug/module/ClientModule.js:
--------------------------------------------------------------------------------
1 | var __reflect = (this && this.__reflect) || function (p, c, t) {
2 | p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t;
3 | };
4 | var ClientModule = (function () {
5 | function ClientModule() {
6 | this.Version = "1.0"; // 当前版本
7 | this.Channel = "REG"; // 账号渠道
8 | this.AppName = "WX_5E8A"; // 游戏包名
9 | this.User = "admin"; // 帐号名 openid
10 | this.RoomType = "RM_DDZ"; // 请求进入的游戏名字
11 | this.UserInfo = new JsonUser();
12 | }
13 | ClientModule.GetInstance = function () {
14 | if (this.__self == null) {
15 | this.__self = new ClientModule();
16 | }
17 | return this.__self;
18 | };
19 | return ClientModule;
20 | }());
21 | __reflect(ClientModule.prototype, "ClientModule");
22 | //# sourceMappingURL=ClientModule.js.map
--------------------------------------------------------------------------------
/EgretWebSocket/bin-debug/module/ClientModule.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"file":"ClientModule.js","sourceRoot":"","sources":["../../src/module/ClientModule.ts"],"names":[],"mappings":";;;AAAA;IAoBC;QAjBA,YAAO,GAAc,KAAK,CAAC,CAA6B,OAAO;QAC5D,YAAO,GAAc,KAAK,CAAC,CAA6B,OAAO;QAC/D,YAAO,GAAc,SAAS,CAAC,CAAsB,OAAO;QAC5D,SAAI,GAAiB,OAAO,CAAC,CAAa,eAAe;QAC5D,aAAQ,GAAW,QAAQ,CAAC,CAAQ,YAAY;QAChD,aAAQ,GAAa,IAAI,QAAQ,EAAE,CAAC;IAYZ,CAAC;IAPX,wBAAW,GAAzB;QACO,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,CAAC,CAAC;YACtB,IAAI,CAAC,MAAM,GAAG,IAAI,YAAY,EAAE,CAAC;QACrC,CAAC;QACD,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC;IACvB,CAAC;IAIL,mBAAC;AAAD,CAAC,AAtBD,IAsBC;AAtBK,UAAA,YAAY,2BAsBjB,CAAA"}
--------------------------------------------------------------------------------
/EgretWebSocket/bin-debug/module/Json/JsonUser.js:
--------------------------------------------------------------------------------
1 | var __reflect = (this && this.__reflect) || function (p, c, t) {
2 | p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t;
3 | };
4 | var JsonUser = (function () {
5 | function JsonUser() {
6 | }
7 | return JsonUser;
8 | }());
9 | __reflect(JsonUser.prototype, "JsonUser");
10 | //# sourceMappingURL=JsonUser.js.map
--------------------------------------------------------------------------------
/EgretWebSocket/bin-debug/module/Json/JsonUser.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"file":"JsonUser.js","sourceRoot":"","sources":["../../../src/module/Json/JsonUser.ts"],"names":[],"mappings":";;;AAAA;IACC;IACA,CAAC;IAUF,eAAC;AAAD,CAAC,AAZD,IAYC;AAZK,UAAA,QAAQ,uBAYb,CAAA"}
--------------------------------------------------------------------------------
/EgretWebSocket/bin-debug/module/LoginModule.js:
--------------------------------------------------------------------------------
1 | var __reflect = (this && this.__reflect) || function (p, c, t) {
2 | p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t;
3 | };
4 | var LoginModule = (function () {
5 | function LoginModule() {
6 | }
7 | LoginModule.prototype.Init = function () {
8 | NetMgr.GetInstance().addEventListener("AuthOk", this.CBAuthOk, this);
9 | };
10 | LoginModule.prototype.CBAuthOk = function () {
11 | console.log("AuthOk回调,进入大厅场景");
12 | };
13 | LoginModule.GetInstance = function () {
14 | if (this.__self == null) {
15 | this.__self = new LoginModule();
16 | }
17 | return this.__self;
18 | };
19 | return LoginModule;
20 | }());
21 | __reflect(LoginModule.prototype, "LoginModule");
22 | //# sourceMappingURL=LoginModule.js.map
--------------------------------------------------------------------------------
/EgretWebSocket/bin-debug/module/LoginModule.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"file":"LoginModule.js","sourceRoot":"","sources":["../../src/module/LoginModule.ts"],"names":[],"mappings":";;;AAAA;IAoBC;IAAuB,CAAC;IAlBjB,0BAAI,GAAX;QACC,MAAM,CAAC,WAAW,EAAE,CAAC,gBAAgB,CAAC,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;IACrE,CAAC;IAEK,8BAAQ,GAAf;QACC,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;IAChC,CAAC;IAKa,uBAAW,GAAzB;QACO,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,CAAC,CAAC;YACtB,IAAI,CAAC,MAAM,GAAG,IAAI,WAAW,EAAE,CAAC;QACpC,CAAC;QACD,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC;IACvB,CAAC;IAIL,kBAAC;AAAD,CAAC,AAtBD,IAsBC;AAtBK,UAAA,WAAW,0BAsBhB,CAAA"}
--------------------------------------------------------------------------------
/EgretWebSocket/bin-debug/module/Player/PlayerDataModule.js:
--------------------------------------------------------------------------------
1 | var __reflect = (this && this.__reflect) || function (p, c, t) {
2 | p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t;
3 | };
4 | var PlayerDataModule = (function () {
5 | function PlayerDataModule() {
6 | }
7 | PlayerDataModule.prototype.Init = function () {
8 | NetMgr.GetInstance().addEventListener("SyncPlayerInfo", this.CBSyncPlayerInfo, this);
9 | };
10 | PlayerDataModule.prototype.CBSyncPlayerInfo = function (event) {
11 | var pb_playerinfo = event.msg.rprotobuf(PB.MsgPlayerInfo);
12 | console.log("SyncPlayerInfo");
13 | console.log(pb_playerinfo);
14 | };
15 | PlayerDataModule.GetInstance = function () {
16 | if (this.__self == null) {
17 | this.__self = new PlayerDataModule();
18 | }
19 | return this.__self;
20 | };
21 | return PlayerDataModule;
22 | }());
23 | __reflect(PlayerDataModule.prototype, "PlayerDataModule");
24 | //# sourceMappingURL=PlayerDataModule.js.map
--------------------------------------------------------------------------------
/EgretWebSocket/bin-debug/module/Player/PlayerDataModule.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"file":"PlayerDataModule.js","sourceRoot":"","sources":["../../../src/module/Player/PlayerDataModule.ts"],"names":[],"mappings":";;;AACA;IA0BC;IAEI,CAAC;IA1BE,+BAAI,GAAX;QACC,MAAM,CAAC,WAAW,EAAE,CAAC,gBAAgB,CAAC,gBAAgB,EAAE,IAAI,CAAC,gBAAgB,EAAE,IAAI,CAAC,CAAC;IACrF,CAAC;IAEK,2CAAgB,GAAvB,UAAyB,KAAe;QAEjC,IAAI,aAAa,GAAqB,KAAK,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,CAAC,aAAa,CAAC,CAAC;QAGlF,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;QACxB,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;IAIlC,CAAC;IAGgB,4BAAW,GAAzB;QACI,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,CAAC,CAAC;YACtB,IAAI,CAAC,MAAM,GAAG,IAAI,gBAAgB,EAAE,CAAC;QACzC,CAAC;QACD,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC;IACvB,CAAC;IAML,uBAAC;AAAD,CAAC,AA9BD,IA8BC;AA9BK,UAAA,gBAAgB,+BA8BrB,CAAA"}
--------------------------------------------------------------------------------
/EgretWebSocket/bin-debug/network/Message.js:
--------------------------------------------------------------------------------
1 | var __reflect = (this && this.__reflect) || function (p, c, t) {
2 | p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t;
3 | };
4 | var Message = (function () {
5 | function Message(name) {
6 | if (name === void 0) { name = ''; }
7 | this.buff_msg = new egret.ByteArray();
8 | this.buff_msg.endian = egret.Endian.LITTLE_ENDIAN;
9 | this.reset(name);
10 | }
11 | Message.prototype.reset = function (name) {
12 | this.name = name;
13 | this.buff_msg.clear();
14 | this.buff_msg.writeInt(0);
15 | this.buff_msg.writeByte(0);
16 | this.wstring(this.name);
17 | };
18 | Message.prototype.fill = function (val, offset, len) {
19 | this.buff_msg.clear();
20 | this.buff_msg.writeBytes(val, offset, len);
21 | // read name
22 | this.buff_msg.position = 5;
23 | this.name = this.rstring();
24 | };
25 | Message.prototype.wstring = function (val) {
26 | this.wint32(val.length);
27 | this.buff_msg.writeUTFBytes(val);
28 | };
29 | Message.prototype.wint32 = function (val) {
30 | this.buff_msg.writeInt(val);
31 | };
32 | Message.prototype.wuint32 = function (val) {
33 | this.buff_msg.writeUnsignedInt(val);
34 | };
35 | Message.prototype.wint64 = function (val) {
36 | var long = protobuf.util.LongBits.from(val);
37 | this.wuint32(long.lo);
38 | this.wuint32(long.hi);
39 | };
40 | Message.prototype.wdouble = function (val) {
41 | this.buff_msg.writeDouble(val);
42 | };
43 | Message.prototype.wprotobuf = function (pb_type, pb_stru) {
44 | var buff_msg = pb_type.encode(pb_stru).finish();
45 | var egret_buffer = new egret.ByteArray(buff_msg);
46 | this.wint32(egret_buffer.length);
47 | this.buff_msg.writeBytes(egret_buffer, 0, egret_buffer.length);
48 | };
49 | Message.prototype.wjson = function (val) {
50 | this.wstring(JSON.stringify(val));
51 | };
52 | ////////////////////////
53 | Message.prototype.rint32 = function () {
54 | return this.buff_msg.readInt();
55 | };
56 | Message.prototype.ruint32 = function () {
57 | return this.buff_msg.readUnsignedInt();
58 | };
59 | Message.prototype.rdouble = function () {
60 | return this.buff_msg.readDouble();
61 | };
62 | Message.prototype.rstring = function () {
63 | var len = this.rint32();
64 | return this.buff_msg.readUTFBytes(len);
65 | };
66 | Message.prototype.rint64 = function (unsigned) {
67 | var val = new protobuf.util.LongBits(0, 0);
68 | val.hi = this.ruint32();
69 | val.lo = this.ruint32();
70 | return val.toLong(unsigned);
71 | };
72 | Message.prototype.rjson = function () {
73 | var len = this.rint32();
74 | var json_str = this.buff_msg.readUTFBytes(len);
75 | return JSON.parse(json_str);
76 | };
77 | Message.prototype.rprotobuf = function (msg_type) {
78 | var len = this.rint32();
79 | var pb_buffer = new egret.ByteArray();
80 | this.buff_msg.readBytes(pb_buffer, 0, len);
81 | return msg_type.decode(pb_buffer.bytes);
82 | };
83 | return Message;
84 | }());
85 | __reflect(Message.prototype, "Message");
86 | //# sourceMappingURL=Message.js.map
--------------------------------------------------------------------------------
/EgretWebSocket/bin-debug/network/Message.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"file":"Message.js","sourceRoot":"","sources":["../../src/network/Message.ts"],"names":[],"mappings":"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"}
--------------------------------------------------------------------------------
/EgretWebSocket/bin-debug/network/NetEvent.js:
--------------------------------------------------------------------------------
1 | var __reflect = (this && this.__reflect) || function (p, c, t) {
2 | p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t;
3 | };
4 | var __extends = this && this.__extends || function __extends(t, e) {
5 | function r() {
6 | this.constructor = t;
7 | }
8 | for (var i in e) e.hasOwnProperty(i) && (t[i] = e[i]);
9 | r.prototype = e.prototype, t.prototype = new r();
10 | };
11 | var NetEvent = (function (_super) {
12 | __extends(NetEvent, _super);
13 | function NetEvent(type, bubbles, cancelable) {
14 | if (bubbles === void 0) { bubbles = false; }
15 | if (cancelable === void 0) { cancelable = false; }
16 | return _super.call(this, type, bubbles, cancelable) || this;
17 | }
18 | return NetEvent;
19 | }(egret.Event));
20 | __reflect(NetEvent.prototype, "NetEvent");
21 | //# sourceMappingURL=NetEvent.js.map
--------------------------------------------------------------------------------
/EgretWebSocket/bin-debug/network/NetEvent.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"file":"NetEvent.js","sourceRoot":"","sources":["../../src/network/NetEvent.ts"],"names":[],"mappings":";;;;;;;;;;AAAA;IAAuB,4BAAW;IAMjC,kBAAmB,IAAY,EAAE,OAAwB,EAAE,UAA2B;QAArD,wBAAA,EAAA,eAAwB;QAAE,2BAAA,EAAA,kBAA2B;eACrF,kBAAM,IAAI,EAAE,OAAO,EAAE,UAAU,CAAC;IACjC,CAAC;IAGF,eAAC;AAAD,CAAC,AAXD,CAAuB,KAAK,CAAC,KAAK,GAWjC;AAXK,UAAA,QAAQ,uBAWb,CAAA"}
--------------------------------------------------------------------------------
/EgretWebSocket/bin-debug/network/NetMgr.js:
--------------------------------------------------------------------------------
1 | var __reflect = (this && this.__reflect) || function (p, c, t) {
2 | p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t;
3 | };
4 | var __extends = this && this.__extends || function __extends(t, e) {
5 | function r() {
6 | this.constructor = t;
7 | }
8 | for (var i in e) e.hasOwnProperty(i) && (t[i] = e[i]);
9 | r.prototype = e.prototype, t.prototype = new r();
10 | };
11 | // TypeScript file
12 | /**
13 | * 网络管理类
14 | */
15 | var NetMgr = (function (_super) {
16 | __extends(NetMgr, _super);
17 | function NetMgr() {
18 | var _this = _super.call(this) || this;
19 | _this.socket = new egret.WebSocket();
20 | _this.recv_buffer = new egret.ByteArray();
21 | _this.send_buffer = new egret.ByteArray();
22 | _this.temp_msg = new Message();
23 | return _this;
24 | }
25 | NetMgr.GetInstance = function () {
26 | if (this.net == null) {
27 | this.net = new NetMgr();
28 | }
29 | return this.net;
30 | };
31 | NetMgr.prototype.Connect = function (serverurl) {
32 | if (this.socket.connected)
33 | return;
34 | this.socket.type = egret.WebSocket.TYPE_BINARY;
35 | this.socket.addEventListener(egret.ProgressEvent.SOCKET_DATA, this.onReceiveMessage, this);
36 | this.socket.addEventListener(egret.Event.CONNECT, this.onSocketOpen, this);
37 | this.socket.addEventListener(egret.IOErrorEvent.IO_ERROR, this.IOError, this);
38 | this.socket.addEventListener(egret.Event.CLOSE, this.Close, this);
39 | this.socket.connectByUrl(serverurl);
40 | this.conn_url = serverurl;
41 | };
42 | /**
43 | * 发送消息
44 | */
45 | NetMgr.prototype.SendMsg = function (msg) {
46 | try {
47 | if (this.socket.connected) {
48 | this.send_buffer.clear();
49 | this.send_buffer.endian = egret.Endian.BIG_ENDIAN;
50 | this.send_buffer.writeInt(msg.buff_msg.length);
51 | this.send_buffer.endian = egret.Endian.LITTLE_ENDIAN;
52 | this.send_buffer.writeBytes(msg.buff_msg);
53 | this.socket.writeBytes(this.send_buffer, 0, this.send_buffer.length);
54 | this.socket.flush();
55 | }
56 | else {
57 | console.error("网络没有连接");
58 | }
59 | }
60 | catch (e) {
61 | console.error(e);
62 | }
63 | };
64 | NetMgr.prototype.SendPB = function (msg_name, pb_type, pb_stru) {
65 | this.temp_msg.reset(msg_name);
66 | this.temp_msg.wprotobuf(pb_type, pb_stru);
67 | this.SendMsg(this.temp_msg);
68 | };
69 | NetMgr.prototype.GetStatus = function () {
70 | return this.socket.connected;
71 | };
72 | NetMgr.prototype.onReceiveMessage = function () {
73 | this.socket.readBytes(this.recv_buffer, this.recv_buffer.position);
74 | if (this.recv_buffer.bytesAvailable > 4) {
75 | this.recv_buffer.endian = egret.Endian.BIG_ENDIAN;
76 | var msg_len = this.recv_buffer.readInt();
77 | this.recv_buffer.endian = egret.Endian.LITTLE_ENDIAN;
78 | if (this.recv_buffer.bytesAvailable >= msg_len) {
79 | var msg = new Message();
80 | msg.fill(this.recv_buffer, this.recv_buffer.position, msg_len);
81 | this.processReceive(msg);
82 | }
83 | else {
84 | console.log("msg len error");
85 | }
86 | this.recv_buffer.clear();
87 | }
88 | };
89 | NetMgr.prototype.processReceive = function (msg) {
90 | console.log("recv msg : " + msg.name);
91 | var netevent = new NetEvent(msg.name);
92 | netevent.msg = msg;
93 | this.dispatchEvent(netevent);
94 | };
95 | NetMgr.prototype.Close = function () {
96 | console.log("连接关闭");
97 | };
98 | NetMgr.prototype.onSocketOpen = function () {
99 | console.log("网络连接成功,发送LOGIN。");
100 | var user = ClientModule.GetInstance().UserInfo;
101 | var pb_login = PB.MsgLogin.create();
102 | pb_login.Version = ClientModule.GetInstance().Version;
103 | pb_login.Channel = ClientModule.GetInstance().Channel;
104 | pb_login.AppName = ClientModule.GetInstance().AppName;
105 | pb_login.User = user.User;
106 | pb_login.NonceStr = user.NonceStr;
107 | pb_login.Token = user.Token;
108 | pb_login.Timestamp = user.Timestamp;
109 | pb_login.UID = user.UID;
110 | pb_login.RoomType = ClientModule.GetInstance().RoomType;
111 | NetMgr.GetInstance().SendPB("LOGIN", PB.MsgLogin, pb_login);
112 | };
113 | NetMgr.prototype.IOError = function () {
114 | console.log("网络连接断开");
115 | };
116 | return NetMgr;
117 | }(egret.DisplayObject));
118 | __reflect(NetMgr.prototype, "NetMgr");
119 | //# sourceMappingURL=NetMgr.js.map
--------------------------------------------------------------------------------
/EgretWebSocket/bin-debug/network/NetMgr.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"file":"NetMgr.js","sourceRoot":"","sources":["../../src/network/NetMgr.ts"],"names":[],"mappings":"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"}
--------------------------------------------------------------------------------
/EgretWebSocket/egretProperties.json:
--------------------------------------------------------------------------------
1 | {
2 | "engineVersion": "5.1.9",
3 | "compilerVersion": "5.1.9",
4 | "template": {},
5 | "target": {
6 | "current": "web"
7 | },
8 | "modules": [
9 | {
10 | "name": "egret"
11 | },
12 | {
13 | "name": "game"
14 | },
15 | {
16 | "name": "tween"
17 | },
18 | {
19 | "name": "assetsmanager"
20 | },
21 | {
22 | "name": "socket"
23 | },
24 | {
25 | "name": "promise"
26 | },
27 | {
28 | "name": "protobuf-lib",
29 | "path": "../ExternalLibs/ProtobufLib/"
30 | },
31 | {
32 | "name": "protobuf-msg",
33 | "path": "../ExternalLibs/ProtobufMsg/"
34 | }
35 | ]
36 | }
--------------------------------------------------------------------------------
/EgretWebSocket/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li9chuan/EgretWebSocket/d72c82d6c26d77851c705444e7c9f0143fc249d8/EgretWebSocket/favicon.ico
--------------------------------------------------------------------------------
/EgretWebSocket/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Egret
7 |
8 |
9 |
10 |
11 |
12 |
13 |
23 |
24 |
25 |
26 |
36 |
37 |
38 |
39 |
40 |
41 |
97 |
98 |
99 |
--------------------------------------------------------------------------------
/EgretWebSocket/libs/modules/promise/promise.min.js:
--------------------------------------------------------------------------------
1 | !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.ES6Promise=e()}(this,function(){"use strict";function t(t){return"function"==typeof t||"object"==typeof t&&null!==t}function e(t){return"function"==typeof t}function n(t){I=t}function r(t){J=t}function o(){return function(){return process.nextTick(a)}}function i(){return"undefined"!=typeof H?function(){H(a)}:c()}function s(){var t=0,e=new V(a),n=document.createTextNode("");return e.observe(n,{characterData:!0}),function(){n.data=t=++t%2}}function u(){var t=new MessageChannel;return t.port1.onmessage=a,function(){return t.port2.postMessage(0)}}function c(){var t=setTimeout;return function(){return t(a,1)}}function a(){for(var t=0;G>t;t+=2){var e=$[t],n=$[t+1];e(n),$[t]=void 0,$[t+1]=void 0}G=0}function f(){try{var t=require,e=t("vertx");return H=e.runOnLoop||e.runOnContext,i()}catch(n){return c()}}function l(t,e){var n=arguments,r=this,o=new this.constructor(p);void 0===o[ee]&&k(o);var i=r._state;return i?!function(){var t=n[i-1];J(function(){return x(i,o,t,r._result)})}():E(r,o,t,e),o}function h(t){var e=this;if(t&&"object"==typeof t&&t.constructor===e)return t;var n=new e(p);return w(n,t),n}function p(){}function v(){return new TypeError("You cannot resolve a promise with itself")}function d(){return new TypeError("A promises callback cannot return that same promise.")}function _(t){try{return t.then}catch(e){return ie.error=e,ie}}function y(t,e,n,r){try{t.call(e,n,r)}catch(o){return o}}function m(t,e,n){J(function(t){var r=!1,o=y(n,e,function(n){r||(r=!0,e!==n?w(t,n):S(t,n))},function(e){r||(r=!0,j(t,e))},"Settle: "+(t._label||" unknown promise"));!r&&o&&(r=!0,j(t,o))},t)}function b(t,e){e._state===re?S(t,e._result):e._state===oe?j(t,e._result):E(e,void 0,function(e){return w(t,e)},function(e){return j(t,e)})}function g(t,n,r){n.constructor===t.constructor&&r===l&&n.constructor.resolve===h?b(t,n):r===ie?j(t,ie.error):void 0===r?S(t,n):e(r)?m(t,n,r):S(t,n)}function w(e,n){e===n?j(e,v()):t(n)?g(e,n,_(n)):S(e,n)}function A(t){t._onerror&&t._onerror(t._result),P(t)}function S(t,e){t._state===ne&&(t._result=e,t._state=re,0!==t._subscribers.length&&J(P,t))}function j(t,e){t._state===ne&&(t._state=oe,t._result=e,J(A,t))}function E(t,e,n,r){var o=t._subscribers,i=o.length;t._onerror=null,o[i]=e,o[i+re]=n,o[i+oe]=r,0===i&&t._state&&J(P,t)}function P(t){var e=t._subscribers,n=t._state;if(0!==e.length){for(var r=void 0,o=void 0,i=t._result,s=0;si;i++)e.resolve(t[i]).then(n,r)}:function(t,e){return e(new TypeError("You must pass an array to race."))})}function K(t){var e=this,n=new e(p);return j(n,t),n}function L(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function N(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function U(t){this[ee]=O(),this._result=this._state=void 0,this._subscribers=[],p!==t&&("function"!=typeof t&&L(),this instanceof U?C(this,t):N())}function W(){var t=void 0;if("undefined"!=typeof global)t=global;else if("undefined"!=typeof self)t=self;else try{t=Function("return this")()}catch(e){throw new Error("polyfill failed because global object is unavailable in this environment")}var n=t.Promise;if("undefined"!=typeof egret_native&&egret_native.capability&&!egret_native.capability("Promise")&&(n=void 0),n){var r=null;try{r=Object.prototype.toString.call(n.resolve())}catch(e){}if("[object Promise]"===r&&!n.cast)return}t.Promise=U}var z=void 0;z=Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)};var B=z,G=0,H=void 0,I=void 0,J=function(t,e){$[G]=t,$[G+1]=e,G+=2,2===G&&(I?I(a):te())},Q="undefined"!=typeof window?window:void 0,R=Q||{},V=R.MutationObserver||R.WebKitMutationObserver,X="undefined"==typeof self&&"undefined"!=typeof process&&"[object process]"==={}.toString.call(process),Z="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,$=new Array(1e3),te=void 0;te=X?o():V?s():Z?u():void 0===Q&&"function"==typeof require?f():c();var ee=Math.random().toString(36).substring(16),ne=void 0,re=1,oe=2,ie=new T,se=new T,ue=0;return Y.prototype._enumerate=function(){for(var t=this.length,e=this._input,n=0;this._state===ne&&t>n;n++)this._eachEntry(e[n],n)},Y.prototype._eachEntry=function(t,e){var n=this._instanceConstructor,r=n.resolve;if(r===h){var o=_(t);if(o===l&&t._state!==ne)this._settledAt(t._state,e,t._result);else if("function"!=typeof o)this._remaining--,this._result[e]=t;else if(n===U){var i=new n(p);g(i,t,o),this._willSettleAt(i,e)}else this._willSettleAt(new n(function(e){return e(t)}),e)}else this._willSettleAt(r(t),e)},Y.prototype._settledAt=function(t,e,n){var r=this.promise;r._state===ne&&(this._remaining--,t===oe?j(r,n):this._result[e]=n),0===this._remaining&&S(r,this._result)},Y.prototype._willSettleAt=function(t,e){var n=this;E(t,void 0,function(t){return n._settledAt(re,e,t)},function(t){return n._settledAt(oe,e,t)})},U.all=F,U.race=D,U.resolve=h,U.reject=K,U._setScheduler=n,U._setAsap=r,U._asap=J,U.prototype={constructor:U,then:l,"catch":function(t){return this.then(null,t)}},U.polyfill=W,U.Promise=U,U}),ES6Promise.polyfill();
--------------------------------------------------------------------------------
/EgretWebSocket/libs/modules/socket/socket.min.js:
--------------------------------------------------------------------------------
1 | var __reflect=this&&this.__reflect||function(t,e,n){t.__class__=e,n?n.push(e):n=[e],t.__types__=t.__types__?n.concat(t.__types__):n},__extends=this&&this.__extends||function(t,e){function n(){this.constructor=t}for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o]);n.prototype=e.prototype,t.prototype=new n},egret;!function(t){}(egret||(egret={}));var egret;!function(t){var e=function(e){function n(o,i){void 0===o&&(o=""),void 0===i&&(i=0);var s=e.call(this)||this;return s._writeMessage="",s._readMessage="",s._connected=!1,s._connecting=!1,s._isReadySend=!1,s._bytesWrite=!1,s._type=n.TYPE_STRING,s._connected=!1,s._writeMessage="",s._readMessage="",s.socket=new t.ISocket,s.socket.addCallBacks(s.onConnect,s.onClose,s.onSocketData,s.onError,s),s}return __extends(n,e),n.prototype.connect=function(t,e){this._connecting||this._connected||(this._connecting=!0,this.socket.connect(t,e))},n.prototype.connectByUrl=function(t){this._connecting||this._connected||(this._connecting=!0,this.socket.connectByUrl(t))},n.prototype.close=function(){this._connected&&this.socket.close()},n.prototype.onConnect=function(){this._connected=!0,this._connecting=!1,this.dispatchEventWith(t.Event.CONNECT)},n.prototype.onClose=function(){this._connected=!1,this.dispatchEventWith(t.Event.CLOSE)},n.prototype.onError=function(){this._connecting&&(this._connecting=!1),this.dispatchEventWith(t.IOErrorEvent.IO_ERROR)},n.prototype.onSocketData=function(e){"string"==typeof e?this._readMessage+=e:this._readByte._writeUint8Array(new Uint8Array(e)),t.ProgressEvent.dispatchProgressEvent(this,t.ProgressEvent.SOCKET_DATA)},n.prototype.flush=function(){return this._connected?(this._writeMessage&&(this.socket.send(this._writeMessage),this._writeMessage=""),this._bytesWrite&&(this.socket.send(this._writeByte.buffer),this._bytesWrite=!1,this._writeByte.clear()),void(this._isReadySend=!1)):void t.$warn(3101)},n.prototype.writeUTF=function(e){return this._connected?(this._type==n.TYPE_BINARY?(this._bytesWrite=!0,this._writeByte.writeUTF(e)):this._writeMessage+=e,void this.flush()):void t.$warn(3101)},n.prototype.readUTF=function(){var t;return this._type==n.TYPE_BINARY?(this._readByte.position=0,t=this._readByte.readUTF(),this._readByte.clear()):(t=this._readMessage,this._readMessage=""),t},n.prototype.writeBytes=function(e,n,o){return void 0===n&&(n=0),void 0===o&&(o=0),this._connected?this._writeByte?(this._bytesWrite=!0,this._writeByte.writeBytes(e,n,o),void this.flush()):void t.$warn(3102):void t.$warn(3101)},n.prototype.readBytes=function(e,n,o){return void 0===n&&(n=0),void 0===o&&(o=0),this._readByte?(this._readByte.position=0,this._readByte.readBytes(e,n,o),void this._readByte.clear()):void t.$warn(3102)},Object.defineProperty(n.prototype,"connected",{get:function(){return this._connected},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"type",{get:function(){return this._type},set:function(e){this._type=e,e!=n.TYPE_BINARY||this._writeByte||(this._readByte=new t.ByteArray,this._writeByte=new t.ByteArray)},enumerable:!0,configurable:!0}),n.TYPE_STRING="webSocketTypeString",n.TYPE_BINARY="webSocketTypeBinary",n}(t.EventDispatcher);t.WebSocket=e,__reflect(e.prototype,"egret.WebSocket")}(egret||(egret={}));var egret;!function(t){var e;!function(e){var n=function(){function e(){this.host="",this.port=0,window.WebSocket||t.$error(3100)}return e.prototype.addCallBacks=function(t,e,n,o,i){this.onConnect=t,this.onClose=e,this.onSocketData=n,this.onError=o,this.thisObject=i},e.prototype.connect=function(t,e){this.host=t,this.port=e;var n="ws://"+this.host+":"+this.port;this.socket=new window.WebSocket(n),this.socket.binaryType="arraybuffer",this._bindEvent()},e.prototype.connectByUrl=function(t){this.socket=new window.WebSocket(t),this.socket.binaryType="arraybuffer",this._bindEvent()},e.prototype._bindEvent=function(){var t=this,e=this.socket;e.onopen=function(){t.onConnect&&t.onConnect.call(t.thisObject)},e.onclose=function(e){t.onClose&&t.onClose.call(t.thisObject)},e.onerror=function(e){t.onError&&t.onError.call(t.thisObject)},e.onmessage=function(e){t.onSocketData&&t.onSocketData.call(t.thisObject,e.data)}},e.prototype.send=function(t){this.socket.send(t)},e.prototype.close=function(){this.socket.close()},e.prototype.disconnect=function(){this.socket.disconnect&&this.socket.disconnect()},e}();e.HTML5WebSocket=n,__reflect(n.prototype,"egret.web.HTML5WebSocket",["egret.ISocket"]),t.ISocket=n}(e=t.web||(t.web={}))}(egret||(egret={}));
--------------------------------------------------------------------------------
/EgretWebSocket/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "initial": [
3 | "libs/modules/egret/egret.js",
4 | "libs/modules/egret/egret.web.js",
5 | "libs/modules/game/game.js",
6 | "libs/modules/tween/tween.js",
7 | "libs/modules/assetsmanager/assetsmanager.js",
8 | "libs/modules/socket/socket.js",
9 | "libs/modules/promise/promise.js"
10 | ],
11 | "game": [
12 | "bin-debug/LoadingUI.js",
13 | "bin-debug/Main.js",
14 | "bin-debug/Platform.js",
15 | "bin-debug/module/ClientModule.js",
16 | "bin-debug/module/LoginModule.js",
17 | "bin-debug/module/Json/JsonUser.js",
18 | "bin-debug/module/Player/PlayerDataModule.js",
19 | "bin-debug/network/Message.js",
20 | "bin-debug/network/NetEvent.js",
21 | "bin-debug/network/NetMgr.js"
22 | ]
23 | }
--------------------------------------------------------------------------------
/EgretWebSocket/resource/assets/bg.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li9chuan/EgretWebSocket/d72c82d6c26d77851c705444e7c9f0143fc249d8/EgretWebSocket/resource/assets/bg.jpg
--------------------------------------------------------------------------------
/EgretWebSocket/resource/assets/egret_icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/li9chuan/EgretWebSocket/d72c82d6c26d77851c705444e7c9f0143fc249d8/EgretWebSocket/resource/assets/egret_icon.png
--------------------------------------------------------------------------------
/EgretWebSocket/resource/config/description.json:
--------------------------------------------------------------------------------
1 | [
2 | "Open-source,Free,Multi-platform",
3 | "Push Game Forward",
4 | "HTML5 Game Engine"
5 | ]
--------------------------------------------------------------------------------
/EgretWebSocket/resource/default.res.json:
--------------------------------------------------------------------------------
1 | {
2 | "groups":[
3 | {
4 | "keys":"bg_jpg,egret_icon_png,description_json",
5 | "name":"preload"
6 | }],
7 | "resources":[
8 | {
9 | "name":"bg_jpg",
10 | "type":"image",
11 | "url":"assets/bg.jpg"
12 | },
13 | {
14 | "name":"egret_icon_png",
15 | "type":"image",
16 | "url":"assets/egret_icon.png"
17 | },
18 | {
19 | "name":"description_json",
20 | "type":"json",
21 | "url":"config/description.json"
22 | }]
23 | }
--------------------------------------------------------------------------------
/EgretWebSocket/scripts/api.d.ts:
--------------------------------------------------------------------------------
1 |
2 | /**
3 | * ResourceManager 配置文件
4 | */
5 | type ResourceManagerConfig = {
6 | /**
7 | * 构建与发布配置
8 | */
9 | buildConfig: (param: BuildConfigParam) => UserConfig,
10 | /**
11 | * 设置资源类型
12 | */
13 | typeSelector: (path: string) => (string | null | undefined)
14 | /**
15 | * 设置资源的合并策略
16 | */
17 | mergeSelector?: (path: string) => (string | null | undefined),
18 | /**
19 | * 设置资源的命名策略
20 | * beta 功能,请勿随意使用
21 | */
22 | nameSelector?: (path: string) => (string | null | undefined)
23 | }
24 | /**
25 | * 构建配置
26 | */
27 | type UserConfig = {
28 | /**
29 | * 输出路径
30 | */
31 | outputDir: string,
32 | /**
33 | * 插件
34 | */
35 | commands: (string | plugins.Command) []
36 | }
37 |
38 | type BuildConfigParam = {
39 |
40 |
41 | /**
42 | * 当前命令,build 或者 command
43 | */
44 | readonly command: string;
45 |
46 | /**
47 | * 发布平台
48 | */
49 | readonly target: string;
50 |
51 | /**
52 | * 开发者指定的版本号
53 | */
54 | readonly version: string;
55 |
56 | /**
57 | * 项目名称
58 | */
59 | readonly projectName: string;
60 |
61 | /**
62 | * 项目路径
63 | */
64 | readonly projectRoot: string;
65 |
66 | /**
67 | * 项目配置
68 | */
69 | readonly projectConfig: ProjectConfig;
70 | }
71 |
72 | type ProjectConfig = {
73 | entryClassName: string;
74 | orientation: string;
75 | frameRate: number;
76 | scaleMode: string;
77 | contentWidth: number;
78 | contentHeight: number;
79 | showFPS: boolean;
80 | fpsStyles: string;
81 | showLog: boolean;
82 | maxTouches: number;
83 | }
84 |
85 |
86 | declare namespace plugins {
87 |
88 | interface CommandContext {
89 |
90 | /**
91 | * 可以用此接口进行文件创建
92 | */
93 | createFile(relativeFilePath: string, contents: Buffer);
94 |
95 | /**
96 | * 构建配置
97 | */
98 | buildConfig: BuildConfigParam;
99 |
100 | /**
101 | * 项目绝对路径
102 | */
103 | projectRoot: string;
104 |
105 | /**
106 | * 项目输出绝对路径
107 | */
108 | outputDir: string;
109 |
110 | }
111 |
112 | /**
113 | * 构建管线命令
114 | */
115 | interface Command {
116 |
117 | /**
118 | * 项目中的每个文件都会执行此函数,返回 file 表示保留此文件,返回 null 表示将此文件从构建管线中删除,即不会发布
119 | */
120 | onFile?(file: File): Promise
121 |
122 | /**
123 | * 项目中所有文件均执行完后,最终会执行此函数。
124 | * 这个函数主要被用于创建新文件
125 | */
126 | onFinish?(pluginContext?: CommandContext): Promise
127 |
128 | [options: string]: any;
129 | }
130 |
131 | interface File {
132 |
133 | /**
134 | * 文件内容的二进制流,如果开发者需要修改文件内容,请修改此属性
135 | */
136 | contents: Buffer;
137 |
138 |
139 | /**
140 | * 文件绝对路径,如果开发者需要对文件进行重命名,请修改此属性
141 | */
142 | path: string;
143 |
144 | /**
145 | * 文件所在的项目的项目路径
146 | */
147 | readonly base: string;
148 |
149 | /**
150 | * 文件的相对于 base 属性的相对路径
151 | */
152 | readonly relative: string;
153 |
154 |
155 | /**
156 | * 文件变更历史,history[0] 即 origin 属性
157 | */
158 | readonly history: ReadonlyArray;
159 |
160 |
161 | /**
162 | * 文件所在的文件夹的绝对路径
163 | */
164 | readonly dirname: string;
165 |
166 | /**
167 | * 文件的文件名
168 | */
169 | readonly basename: string;
170 |
171 |
172 | /**
173 | * 文件的扩展名
174 | */
175 | readonly extname: string;
176 |
177 | /**
178 | * 文件的初始文件名
179 | */
180 | readonly origin: string;
181 |
182 | /**
183 | * 其他自定义属性
184 | */
185 | [customProperty: string]: any;
186 |
187 | }
188 |
189 | }
190 |
191 |
192 |
193 |
194 |
195 |
196 |
197 |
198 |
199 |
200 | declare module 'built-in' {
201 |
202 | /**
203 | * 混淆插件参数,设置源代码和目标代码
204 | */
205 | type UglifyPluginOption = { sources: string[], target: string };
206 |
207 | type UglifyPluginOptions = UglifyPluginOption[];
208 |
209 | /**
210 | * 混淆插件
211 | */
212 | export class UglifyPlugin implements plugins.Command {
213 |
214 | constructor(mergeSelector: UglifyPluginOptions);
215 |
216 | }
217 |
218 |
219 | type LibraryType = "debug" | "release";
220 |
221 | type CompilePluginOptions = { libraryType: LibraryType, defines?: any };
222 | /**
223 | * 编译命令
224 | */
225 | export class CompilePlugin implements plugins.Command {
226 |
227 | constructor(options: CompilePluginOptions);
228 | }
229 |
230 | /**
231 | * EXML 插件,用于发布 EXML 文件
232 | */
233 | export class ExmlPlugin implements plugins.Command {
234 |
235 | constructor(publishPolicy: EXML_Publish_Policy);
236 |
237 | }
238 |
239 | /**
240 | * 发布策略
241 | * * default : 使用 egretProperties.json 中的 exmlPublishPolicy 中的策略
242 | * * debug : 默认策略,用于开发环境
243 | * * contents : 将 EXML 的内容写入到主题文件中
244 | * * gjs : 将生成的JS文件写入到主题文件中
245 | * * commonjs : 将EXML合并为一个 CommonJS 风格的文件
246 | */
247 | type EXML_Publish_Policy = "default" | "debug" | "contents" | "gjs" | "commonjs"
248 |
249 |
250 |
251 |
252 | /**
253 | * 生成 manifest 文件,这个文件会被用于记录 JavaScript 文件的版本号
254 | */
255 | export class ManifestPlugin implements plugins.Command {
256 | constructor(options?: ManifestPluginOptions)
257 | }
258 |
259 | /**
260 | * 生成文件的文件名
261 | * 支持 json 与 js 两种格式
262 | */
263 | type ManifestPluginOptions = {
264 |
265 | output: string,
266 |
267 | hash?: "crc32",
268 |
269 | /**
270 | * 是否输出转换过程
271 | */
272 | verbose?: boolean
273 |
274 |
275 | }
276 |
277 | /**
278 | * EmitResConfigFilePlugin 的参数
279 | * * output: 生成路径,可以指定生成为 *.res.js 文件或者 *.res.json 文件
280 | * * typeSelector: 根据文件路径决定文件类型
281 | * * nameSelector: 根据文件路径决定文件的资源名
282 | * * groupSelector: 根据文件路径决定资源所述的资源组
283 | */
284 | type EmitResConfigFilePluginOptions = {
285 | output: string,
286 | typeSelector: (path: string) => string | null | undefined,
287 | nameSelector: (path: string) => string | null | undefined,
288 | groupSelector: (path: string) => string | null | undefined,
289 | }
290 |
291 |
292 | /**
293 | * 生成 res.json 文件或者 res.js 文件
294 | */
295 | export class EmitResConfigFilePlugin implements plugins.Command {
296 |
297 | constructor(options: EmitResConfigFilePluginOptions)
298 |
299 | }
300 |
301 |
302 | /**
303 | * 增量编译
304 | * 这个插件生成的 JavaScript 代码不会被添加到构建管线中,后续其他插件无法获取生成的 js 文件
305 | * 这个功能将会在未来被 watch 模式代替掉
306 | */
307 | export class IncrementCompilePlugin implements plugins.Command {
308 |
309 | }
310 |
311 | /**
312 | * 使用 TextureMerger 实现纹理自动合并,依赖 TextureMerger 1.7 以上的版本
313 | */
314 | export class TextureMergerPlugin implements plugins.Command {
315 |
316 | constructor();
317 |
318 | }
319 |
320 | type CleanPluginOptions = {
321 |
322 | matchers: string[]
323 | }
324 |
325 |
326 | export class CleanPlugin implements plugins.Command {
327 | constructor(options: CleanPluginOptions);
328 | }
329 |
330 | type RenamePluginOptions = {
331 |
332 | verbose?: boolean
333 |
334 | hash?: "crc32"
335 |
336 | matchers: { from: string, to: string }[]
337 | }
338 | export class RenamePlugin implements plugins.Command {
339 | constructor(options: RenamePluginOptions);
340 | }
341 |
342 | type ResSplitPluginOptions = {
343 |
344 | verbose?: boolean
345 |
346 | matchers: { from: string, to: string }[]
347 | }
348 |
349 | export class ResSplitPlugin implements plugins.Command {
350 | constructor(options: ResSplitPluginOptions);
351 | }
352 |
353 | }
--------------------------------------------------------------------------------
/EgretWebSocket/scripts/bricks/bricks.ts:
--------------------------------------------------------------------------------
1 | import * as fs from 'fs';
2 | import * as path from 'path';
3 |
4 |
5 | type ManifestConfig = {
6 |
7 | initial: string[],
8 |
9 | game: string[]
10 |
11 | }
12 |
13 | export class BricksPlugin implements plugins.Command {
14 |
15 | constructor() {
16 | }
17 | async onFile(file: plugins.File) {
18 | const filename = file.origin;
19 | if (filename == 'manifest.json') {
20 | const contents = file.contents.toString();
21 | const jsonData: ManifestConfig = JSON.parse(contents);
22 |
23 | let content = '';
24 |
25 | for (let item of jsonData.initial) {
26 | if (item != 'js/promise.js' && item != 'js/promise.min.js') {
27 | content += `BK.Script.loadlib("GameRes://${item}");\n`
28 | }
29 | if (item == "js/egret.js" || item == 'js/egret.min.js') {
30 | content += `BK.Script.loadlib("GameRes://egret.bricks.js");\n`
31 | }
32 | }
33 | for (let item of jsonData.game) {
34 | content += `BK.Script.loadlib("GameRes://${item}");\n`
35 | }
36 | file.path = file.dirname + '/manifest.js'
37 | file.contents = new Buffer(content);
38 | } else if (filename == 'main.js') {
39 | const content = file.contents.toString();
40 | let result = content.replace(/RES\.loadConfig\("resource\/default\.res\.json", "resource\/"\)/gm, 'RES.loadConfig("GameRes://resource/default.res.json", "GameRes://resource/")');
41 | result = result.replace(/eui\.Theme\("resource\/default\.thm\.json", _this\.stage\)/gm, 'eui.Theme("GameRes://resource/default.thm.json", _this.stage)');
42 | file.path = file.dirname + '/main.js'
43 | file.contents = new Buffer(result);
44 | }
45 | return file;
46 | }
47 | async onFinish(pluginContext) {
48 |
49 | }
50 | }
--------------------------------------------------------------------------------
/EgretWebSocket/scripts/config.android.ts:
--------------------------------------------------------------------------------
1 | /// 阅读 api.d.ts 查看文档
2 | ///
3 |
4 | import * as path from 'path';
5 | import { UglifyPlugin, CompilePlugin, ManifestPlugin, ExmlPlugin, EmitResConfigFilePlugin, TextureMergerPlugin } from 'built-in';
6 | import { BricksPlugin } from './bricks/bricks';
7 | import { CustomPlugin } from './myplugin';
8 | import * as defaultConfig from './config';
9 |
10 | const config: ResourceManagerConfig = {
11 |
12 | buildConfig: (params) => {
13 |
14 | const { target, command, projectName, version } = params;
15 | const outputDir = `../${projectName}_android/assets/game`;
16 | return {
17 | outputDir,
18 | commands: [
19 | // new CompilePlugin({ libraryType: "debug", defines: { DEBUG: false, RELEASE: true } }),
20 | new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
21 | new CompilePlugin({ libraryType: "release", defines: { DEBUG: false, RELEASE: true } }),
22 | new UglifyPlugin([{
23 | sources: ["main.js"],
24 | target: "main.min.js"
25 | }]),
26 | new ManifestPlugin({ output: 'manifest.json' })
27 | ]
28 | }
29 | },
30 |
31 | mergeSelector: defaultConfig.mergeSelector,
32 |
33 | typeSelector: defaultConfig.typeSelector
34 | }
35 |
36 |
37 |
38 | export = config;
39 |
--------------------------------------------------------------------------------
/EgretWebSocket/scripts/config.bricks.ts:
--------------------------------------------------------------------------------
1 | /// 阅读 api.d.ts 查看文档
2 | ///
3 |
4 | import * as path from 'path';
5 | import { UglifyPlugin, CompilePlugin, ManifestPlugin, ExmlPlugin, EmitResConfigFilePlugin, TextureMergerPlugin } from 'built-in';
6 | import { BricksPlugin } from './bricks/bricks';
7 | import { CustomPlugin } from './myplugin';
8 | import * as defaultConfig from './config';
9 |
10 | const config: ResourceManagerConfig = {
11 |
12 | buildConfig: (params) => {
13 |
14 | const { target, command, projectName, version } = params;
15 | const outputDir = `../${projectName}_bricks/PublicBrickEngineGame/Res`;
16 | return {
17 | outputDir,
18 | commands: [
19 | new CompilePlugin({ libraryType: "debug", defines: { DEBUG: true, RELEASE: false } }),
20 | new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
21 | new ManifestPlugin({ output: 'manifest.json' }),
22 | new BricksPlugin()
23 | ]
24 | }
25 | },
26 |
27 | mergeSelector: defaultConfig.mergeSelector,
28 |
29 | typeSelector: defaultConfig.typeSelector
30 | }
31 |
32 |
33 |
34 | export = config;
35 |
--------------------------------------------------------------------------------
/EgretWebSocket/scripts/config.ios.ts:
--------------------------------------------------------------------------------
1 | /// 阅读 api.d.ts 查看文档
2 | ///
3 |
4 | import * as path from 'path';
5 | import { UglifyPlugin, CompilePlugin, ManifestPlugin, ExmlPlugin, EmitResConfigFilePlugin, TextureMergerPlugin } from 'built-in';
6 | import { BricksPlugin } from './bricks/bricks';
7 | import { CustomPlugin } from './myplugin';
8 | import * as defaultConfig from './config';
9 |
10 | const config: ResourceManagerConfig = {
11 |
12 | buildConfig: (params) => {
13 |
14 | const { target, command, projectName, version } = params;
15 | const outputDir = `../${projectName}_ios/assets/game`;
16 | return {
17 | outputDir,
18 | commands: [
19 | new CompilePlugin({ libraryType: "debug", defines: { DEBUG: false, RELEASE: true } }),
20 | new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
21 | new CompilePlugin({ libraryType: "release", defines: { DEBUG: false, RELEASE: true } }),
22 | new UglifyPlugin([{
23 | sources: ["main.js"],
24 | target: "main.min.js"
25 | }]),
26 | new ManifestPlugin({ output: 'manifest.json' })
27 | ]
28 | }
29 | },
30 |
31 | mergeSelector: defaultConfig.mergeSelector,
32 |
33 | typeSelector: defaultConfig.typeSelector
34 | }
35 |
36 |
37 |
38 | export = config;
39 |
--------------------------------------------------------------------------------
/EgretWebSocket/scripts/config.ts:
--------------------------------------------------------------------------------
1 | /// 阅读 api.d.ts 查看文档
2 | ///
3 |
4 | import * as path from 'path';
5 | import { UglifyPlugin, IncrementCompilePlugin, CompilePlugin, ManifestPlugin, ExmlPlugin, EmitResConfigFilePlugin, TextureMergerPlugin } from 'built-in';
6 | import { WxgamePlugin } from './wxgame/wxgame';
7 | import { BricksPlugin } from './bricks/bricks';
8 | import { CustomPlugin } from './myplugin';
9 |
10 | const config: ResourceManagerConfig = {
11 |
12 |
13 | buildConfig: (params) => {
14 |
15 | const { target, command, projectName, version } = params;
16 |
17 | if (command == 'build') {
18 | const outputDir = '.';
19 | return {
20 | outputDir,
21 | commands: [
22 | // new EmitResConfigFilePlugin({
23 | // output: "resource/default.res.json",
24 | // typeSelector: config.typeSelector,
25 | // nameSelector: p => path.basename(p).replace(/\./gi, "_"),
26 | // groupSelector: p => "preload"
27 | // }),
28 | new ExmlPlugin('debug'), // 非 EUI 项目关闭此设置
29 | new IncrementCompilePlugin(),
30 | ]
31 | }
32 | }
33 | else if (command == 'publish') {
34 | const outputDir = `bin-release/web/${version}`;
35 | return {
36 | outputDir,
37 | commands: [
38 | new CustomPlugin(),
39 | new CompilePlugin({ libraryType: "release", defines: { DEBUG: false, RELEASE: true } }),
40 | new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
41 | new UglifyPlugin([{
42 | sources: ["main.js"],
43 | target: "main.min.js"
44 | }]),
45 | new ManifestPlugin({ output: "manifest.json", hash: "crc32" })
46 | ]
47 | }
48 | }
49 | else {
50 | throw `unknown command : ${params.command}`
51 | }
52 | },
53 |
54 | mergeSelector: (path) => {
55 | if (path.indexOf("assets/bitmap/") >= 0) {
56 | return "assets/bitmap/sheet.sheet"
57 | }
58 | else if (path.indexOf("armature") >= 0 && path.indexOf(".json") >= 0) {
59 | return "assets/armature/1.zip";
60 | }
61 | },
62 |
63 | typeSelector: (path) => {
64 | const ext = path.substr(path.lastIndexOf(".") + 1);
65 | const typeMap = {
66 | "jpg": "image",
67 | "png": "image",
68 | "webp": "image",
69 | "json": "json",
70 | "fnt": "font",
71 | "pvr": "pvr",
72 | "mp3": "sound",
73 | "zip": "zip",
74 | "sheet": "sheet",
75 | "exml": "text"
76 | }
77 | let type = typeMap[ext];
78 | if (type == "json") {
79 | if (path.indexOf("sheet") >= 0) {
80 | type = "sheet";
81 | } else if (path.indexOf("movieclip") >= 0) {
82 | type = "movieclip";
83 | };
84 | }
85 | return type;
86 | }
87 | }
88 |
89 |
90 | export = config;
91 |
--------------------------------------------------------------------------------
/EgretWebSocket/scripts/config.wxgame.ts:
--------------------------------------------------------------------------------
1 | /// 阅读 api.d.ts 查看文档
2 | ///
3 |
4 | import * as path from 'path';
5 | import { UglifyPlugin, CompilePlugin, ManifestPlugin, ExmlPlugin, EmitResConfigFilePlugin, TextureMergerPlugin, CleanPlugin } from 'built-in';
6 | import { WxgamePlugin } from './wxgame/wxgame';
7 | import { CustomPlugin } from './myplugin';
8 | import * as defaultConfig from './config';
9 |
10 | const config: ResourceManagerConfig = {
11 |
12 | buildConfig: (params) => {
13 |
14 | const { target, command, projectName, version } = params;
15 | const outputDir = `../${projectName}_wxgame`;
16 | if (command == 'build') {
17 | return {
18 | outputDir,
19 | commands: [
20 | new CleanPlugin({ matchers: ["js", "resource"] }),
21 | new CompilePlugin({ libraryType: "debug", defines: { DEBUG: true, RELEASE: false } }),
22 | new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
23 | new WxgamePlugin(),
24 | new ManifestPlugin({ output: 'manifest.js' })
25 | ]
26 | }
27 | }
28 | else if (command == 'publish') {
29 | return {
30 | outputDir,
31 | commands: [
32 | new CleanPlugin({ matchers: ["js", "resource"] }),
33 | new CompilePlugin({ libraryType: "release", defines: { DEBUG: false, RELEASE: true } }),
34 | new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
35 | new WxgamePlugin(),
36 | new UglifyPlugin([{
37 | sources: ["main.js"],
38 | target: "main.min.js"
39 | }
40 | ]),
41 | new ManifestPlugin({ output: 'manifest.js' })
42 | ]
43 | }
44 | }
45 | else {
46 | throw `unknown command : ${params.command}`;
47 | }
48 | },
49 |
50 | mergeSelector: defaultConfig.mergeSelector,
51 |
52 | typeSelector: defaultConfig.typeSelector
53 | }
54 |
55 |
56 |
57 | export = config;
58 |
--------------------------------------------------------------------------------
/EgretWebSocket/scripts/myplugin.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * 示例自定义插件,您可以查阅 http://developer.egret.com/cn/2d/projectConfig/cmdExtensionPluginin/
3 | * 了解如何开发一个自定义插件
4 | */
5 | export class CustomPlugin implements plugins.Command {
6 |
7 | constructor() {
8 | }
9 |
10 | async onFile(file: plugins.File) {
11 | return file;
12 | }
13 |
14 | async onFinish(commandContext: plugins.CommandContext) {
15 |
16 | }
17 | }
--------------------------------------------------------------------------------
/EgretWebSocket/scripts/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | /* Basic Options */
4 | "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
5 | "module": "commonjs", /* Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'. */
6 | "lib": [
7 | "es5",
8 | "es2015.promise"
9 | ], /* Specify library files to be included in the compilation: */
10 | "allowJs": true, /* Allow javascript files to be compiled. */
11 | // "checkJs": true, /* Report errors in .js files. */
12 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
13 | // "declaration": true, /* Generates corresponding '.d.ts' file. */
14 | // "sourceMap": true, /* Generates corresponding '.map' file. */
15 | // "outFile": "./", /* Concatenate and emit output to single file. */
16 | // "outDir": "./", /* Redirect output structure to the directory. */
17 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
18 | // "removeComments": true, /* Do not emit comments to output. */
19 | // "noEmit": true, /* Do not emit outputs. */
20 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */
21 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
22 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
23 | /* Strict Type-Checking Options */
24 | "strict": true, /* Enable all strict type-checking options. */
25 | "noImplicitAny": false /* Raise error on expressions and declarations with an implied 'any' type. */
26 | // "strictNullChecks": true, /* Enable strict null checks. */
27 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
28 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
29 | /* Additional Checks */
30 | // "noUnusedLocals": true, /* Report errors on unused locals. */
31 | // "noUnusedParameters": true, /* Report errors on unused parameters. */
32 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
33 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
34 | /* Module Resolution Options */
35 | // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
36 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
37 | /* List of root folders whose combined content represents the structure of the project at runtime. */
38 | // "typeRoots": [], /* List of folders to include type definitions from. */
39 | // "types": [], /* Type declaration files to be included in compilation. */
40 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
41 | /* Source Map Options */
42 | // "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
43 | // "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */
44 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
45 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
46 | /* Experimental Options */
47 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
48 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
49 | }
50 | }
--------------------------------------------------------------------------------
/EgretWebSocket/scripts/wxgame/wxgame.ts:
--------------------------------------------------------------------------------
1 | import * as fs from 'fs';
2 | import * as path from 'path';
3 | export class WxgamePlugin implements plugins.Command {
4 |
5 | constructor() {
6 | }
7 | async onFile(file: plugins.File) {
8 | if (file.extname == '.js') {
9 | const filename = file.origin;
10 | if (filename == "libs/modules/promise/promise.js" || filename == 'libs/modules/promise/promise.min.js') {
11 | return null;
12 | }
13 | if (filename == 'libs/modules/egret/egret.js' || filename == 'libs/modules/egret/egret.min.js') {
14 | let content = file.contents.toString();
15 | content += `;window.egret = egret;`;
16 | content = content.replace(/definition = __global/, "definition = window");
17 | file.contents = new Buffer(content);
18 | }
19 | else {
20 | let content = file.contents.toString();
21 | if (
22 | filename == "libs/modules/res/res.js" ||
23 | filename == 'libs/modules/res/res.min.js' ||
24 | filename == 'libs/modules/assetsmanager/assetsmanager.min.js' ||
25 | filename == 'libs/modules/assetsmanager/assetsmanager.js'
26 | ) {
27 | content += ";window.RES = RES;"
28 | }
29 | if (filename == "libs/modules/eui/eui.js" || filename == 'libs/modules/eui/eui.min.js') {
30 | content += ";window.eui = eui;"
31 | }
32 | if (filename == 'libs/modules/dragonBones/dragonBones.js' || filename == 'libs/modules/dragonBones/dragonBones.min.js') {
33 | content += ';window.dragonBones = dragonBones';
34 | }
35 | content = "var egret = window.egret;" + content;
36 | if (filename == 'main.js') {
37 | content += ";window.Main = Main;"
38 | }
39 | file.contents = new Buffer(content);
40 | }
41 | }
42 | return file;
43 | }
44 | async onFinish(pluginContext: plugins.CommandContext) {
45 | //同步 index.html 配置到 game.js
46 | const gameJSPath = path.join(pluginContext.outputDir, "game.js");
47 | let gameJSContent = fs.readFileSync(gameJSPath, { encoding: "utf8" });
48 | const projectConfig = pluginContext.buildConfig.projectConfig;
49 | const optionStr =
50 | `entryClassName: ${projectConfig.entryClassName},\n\t\t` +
51 | `orientation: ${projectConfig.orientation},\n\t\t` +
52 | `frameRate: ${projectConfig.frameRate},\n\t\t` +
53 | `scaleMode: ${projectConfig.scaleMode},\n\t\t` +
54 | `contentWidth: ${projectConfig.contentWidth},\n\t\t` +
55 | `contentHeight: ${projectConfig.contentHeight},\n\t\t` +
56 | `showFPS: ${projectConfig.showFPS},\n\t\t` +
57 | `fpsStyles: ${projectConfig.fpsStyles},\n\t\t` +
58 | `showLog: ${projectConfig.showLog},\n\t\t` +
59 | `maxTouches: ${projectConfig.maxTouches},`;
60 | const reg = /\/\/----auto option start----[\s\S]*\/\/----auto option end----/;
61 | const replaceStr = '\/\/----auto option start----\n\t\t' + optionStr + '\n\t\t\/\/----auto option end----';
62 | gameJSContent = gameJSContent.replace(reg, replaceStr);
63 | fs.writeFileSync(gameJSPath, gameJSContent);
64 |
65 | //修改横竖屏
66 | let orientation;
67 | if (projectConfig.orientation == '"landscape"') {
68 | orientation = "landscape";
69 | }
70 | else {
71 | orientation = "portrait";
72 | }
73 | const gameJSONPath = path.join(pluginContext.outputDir, "game.json");
74 | let gameJSONContent = JSON.parse(fs.readFileSync(gameJSONPath, { encoding: "utf8" }));
75 | gameJSONContent.deviceOrientation = orientation;
76 | fs.writeFileSync(gameJSONPath, JSON.stringify(gameJSONContent, null, "\t"));
77 | }
78 | }
--------------------------------------------------------------------------------
/EgretWebSocket/src/LoadingUI.ts:
--------------------------------------------------------------------------------
1 | //////////////////////////////////////////////////////////////////////////////////////
2 | //
3 | // Copyright (c) 2014-present, Egret Technology.
4 | // All rights reserved.
5 | // Redistribution and use in source and binary forms, with or without
6 | // modification, are permitted provided that the following conditions are met:
7 | //
8 | // * Redistributions of source code must retain the above copyright
9 | // notice, this list of conditions and the following disclaimer.
10 | // * Redistributions in binary form must reproduce the above copyright
11 | // notice, this list of conditions and the following disclaimer in the
12 | // documentation and/or other materials provided with the distribution.
13 | // * Neither the name of the Egret nor the
14 | // names of its contributors may be used to endorse or promote products
15 | // derived from this software without specific prior written permission.
16 | //
17 | // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
18 | // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 | // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 | // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
21 | // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
23 | // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
24 | // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25 | // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
26 | // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 | //
28 | //////////////////////////////////////////////////////////////////////////////////////
29 |
30 | class LoadingUI extends egret.Sprite implements RES.PromiseTaskReporter {
31 |
32 | public constructor() {
33 | super();
34 | this.createView();
35 | }
36 |
37 | private textField: egret.TextField;
38 |
39 | private createView(): void {
40 | this.textField = new egret.TextField();
41 | this.addChild(this.textField);
42 | this.textField.y = 300;
43 | this.textField.width = 480;
44 | this.textField.height = 100;
45 | this.textField.textAlign = "center";
46 | }
47 |
48 | public onProgress(current: number, total: number): void {
49 | this.textField.text = `Loading...${current}/${total}`;
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/EgretWebSocket/src/Main.ts:
--------------------------------------------------------------------------------
1 | //////////////////////////////////////////////////////////////////////////////////////
2 | //
3 | // Copyright (c) 2014-present, Egret Technology.
4 | // All rights reserved.
5 | // Redistribution and use in source and binary forms, with or without
6 | // modification, are permitted provided that the following conditions are met:
7 | //
8 | // * Redistributions of source code must retain the above copyright
9 | // notice, this list of conditions and the following disclaimer.
10 | // * Redistributions in binary form must reproduce the above copyright
11 | // notice, this list of conditions and the following disclaimer in the
12 | // documentation and/or other materials provided with the distribution.
13 | // * Neither the name of the Egret nor the
14 | // names of its contributors may be used to endorse or promote products
15 | // derived from this software without specific prior written permission.
16 | //
17 | // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
18 | // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 | // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 | // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
21 | // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
23 | // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
24 | // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25 | // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
26 | // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 | //
28 | //////////////////////////////////////////////////////////////////////////////////////
29 |
30 | class Main extends egret.DisplayObjectContainer {
31 |
32 | public constructor() {
33 | super();
34 | this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
35 | }
36 |
37 | private onAddToStage(event: egret.Event) {
38 |
39 | egret.lifecycle.addLifecycleListener((context) => {
40 | // custom lifecycle plugin
41 |
42 | context.onUpdate = () => {
43 |
44 | }
45 | })
46 |
47 | egret.lifecycle.onPause = () => {
48 | egret.ticker.pause();
49 | }
50 |
51 | egret.lifecycle.onResume = () => {
52 | egret.ticker.resume();
53 | }
54 |
55 | this.runGame().catch(e => {
56 | console.log(e);
57 | })
58 |
59 |
60 |
61 | }
62 |
63 | private async runGame() {
64 | await this.loadResource()
65 | this.createGameScene();
66 | const result = await RES.getResAsync("description_json")
67 | this.startAnimation(result);
68 |
69 | LoginModule.GetInstance().Init();
70 | PlayerDataModule.GetInstance().Init();
71 |
72 | await platform.login();
73 | const userInfo = await platform.getUserInfo();
74 | console.log(userInfo);
75 | }
76 |
77 | private async loadResource() {
78 | try {
79 | const loadingView = new LoadingUI();
80 | this.stage.addChild(loadingView);
81 | await RES.loadConfig("resource/default.res.json", "resource/");
82 | await RES.loadGroup("preload", 0, loadingView);
83 | this.stage.removeChild(loadingView);
84 | }
85 | catch (e) {
86 | console.error(e);
87 | }
88 | }
89 |
90 | private textfield: egret.TextField;
91 |
92 | /**
93 | * 创建游戏场景
94 | * Create a game scene
95 | */
96 | private createGameScene() {
97 | let sky = this.createBitmapByName("bg_jpg");
98 | this.addChild(sky);
99 | let stageW = this.stage.stageWidth;
100 | let stageH = this.stage.stageHeight;
101 | sky.width = stageW;
102 | sky.height = stageH;
103 |
104 | let topMask = new egret.Shape();
105 | topMask.graphics.beginFill(0x000000, 0.5);
106 | topMask.graphics.drawRect(0, 0, stageW, 172);
107 | topMask.graphics.endFill();
108 | topMask.y = 33;
109 | this.addChild(topMask);
110 |
111 | let icon = this.createBitmapByName("egret_icon_png");
112 | this.addChild(icon);
113 | icon.x = 26;
114 | icon.y = 33;
115 |
116 | let line = new egret.Shape();
117 | line.graphics.lineStyle(2, 0xffffff);
118 | line.graphics.moveTo(0, 0);
119 | line.graphics.lineTo(0, 117);
120 | line.graphics.endFill();
121 | line.x = 172;
122 | line.y = 61;
123 | this.addChild(line);
124 |
125 |
126 | let colorLabel = new egret.TextField();
127 | colorLabel.textColor = 0xffffff;
128 | colorLabel.width = stageW - 172;
129 | colorLabel.textAlign = "center";
130 | colorLabel.text = "Hello Egret";
131 | colorLabel.size = 24;
132 | colorLabel.x = 172;
133 | colorLabel.y = 80;
134 | this.addChild(colorLabel);
135 |
136 | let textfield = new egret.TextField();
137 | this.addChild(textfield);
138 | textfield.alpha = 0;
139 | textfield.width = stageW - 172;
140 | textfield.textAlign = egret.HorizontalAlign.CENTER;
141 | textfield.size = 24;
142 | textfield.textColor = 0xffffff;
143 | textfield.x = 172;
144 | textfield.y = 135;
145 | this.textfield = textfield;
146 |
147 |
148 | }
149 |
150 | /**
151 | * 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。
152 | * Create a Bitmap object according to name keyword.As for the property of name please refer to the configuration file of resources/resource.json.
153 | */
154 | private createBitmapByName(name: string) {
155 | let result = new egret.Bitmap();
156 | let texture: egret.Texture = RES.getRes(name);
157 | result.texture = texture;
158 | return result;
159 | }
160 |
161 | /**
162 | * 描述文件加载成功,开始播放动画
163 | * Description file loading is successful, start to play the animation
164 | */
165 | private startAnimation(result: string[]) {
166 | let parser = new egret.HtmlTextParser();
167 |
168 | let textflowArr = result.map(text => parser.parse(text));
169 | let textfield = this.textfield;
170 | let count = -1;
171 | let change = () => {
172 | count++;
173 | if (count >= textflowArr.length) {
174 | count = 0;
175 | }
176 | let textFlow = textflowArr[count];
177 |
178 | // 切换描述内容
179 | // Switch to described content
180 | textfield.textFlow = textFlow;
181 | let tw = egret.Tween.get(textfield);
182 | tw.to({ "alpha": 1 }, 200);
183 | tw.wait(2000);
184 | tw.to({ "alpha": 0 }, 200);
185 | tw.call(change, this);
186 | };
187 |
188 | change();
189 | }
190 | }
--------------------------------------------------------------------------------
/EgretWebSocket/src/Platform.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * 平台数据接口。
3 | * 由于每款游戏通常需要发布到多个平台上,所以提取出一个统一的接口用于开发者获取平台数据信息
4 | * 推荐开发者通过这种方式封装平台逻辑,以保证整体结构的稳定
5 | * 由于不同平台的接口形式各有不同,白鹭推荐开发者将所有接口封装为基于 Promise 的异步形式
6 | */
7 | declare interface Platform {
8 |
9 | getUserInfo(): Promise;
10 |
11 | login(): Promise
12 |
13 | }
14 |
15 | class DebugPlatform implements Platform {
16 | async getUserInfo() {
17 | return { nickName: "username" }
18 | }
19 | async login() {
20 |
21 | let user: JsonUser = ClientModule.GetInstance().UserInfo;
22 |
23 | user.NonceStr = "6GosND6R6HCeDWFPGWjQ";
24 | user.Token = "C5F9DB80F40EC9A98EA0E94604091198";
25 | user.UID = 1002;
26 | user.FES = "ws://127.0.0.1:9999";
27 | user.Timestamp = 1523541253;
28 | user.User = "oYsC35RNsWxsYQkKGsZVhxEImRuw";
29 |
30 | ClientModule.GetInstance().Version = "1.0";
31 | ClientModule.GetInstance().Channel = "WX";
32 | ClientModule.GetInstance().AppName = "WX_5E8A";
33 | ClientModule.GetInstance().RoomType = "RM_DDZ";
34 | ClientModule.GetInstance().User = "oYsC35RNsWxsYQkKGsZVhxEImRuw";
35 |
36 | NetMgr.GetInstance().Connect(user.FES);
37 | }
38 | }
39 |
40 |
41 | if (!window.platform) {
42 | window.platform = new DebugPlatform();
43 | }
44 |
45 |
46 |
47 | declare let platform: Platform;
48 |
49 | declare interface Window {
50 |
51 | platform: Platform
52 | }
53 |
54 |
55 |
56 |
57 |
58 |
--------------------------------------------------------------------------------
/EgretWebSocket/src/module/ClientModule.ts:
--------------------------------------------------------------------------------
1 | class ClientModule {
2 |
3 |
4 | Version:string = "1.0"; // 当前版本
5 | Channel:string = "REG"; // 账号渠道
6 | AppName:string = "WX_5E8A"; // 游戏包名
7 | User:string = "admin"; // 帐号名 openid
8 | RoomType:string = "RM_DDZ"; // 请求进入的游戏名字
9 | UserInfo:JsonUser = new JsonUser();
10 |
11 |
12 |
13 |
14 | public static GetInstance(): ClientModule {
15 | if (this.__self == null) {
16 | this.__self = new ClientModule();
17 | }
18 | return this.__self;
19 | }
20 |
21 | private constructor() { }
22 | private static __self: ClientModule;
23 | }
24 |
25 |
--------------------------------------------------------------------------------
/EgretWebSocket/src/module/Json/JsonUser.ts:
--------------------------------------------------------------------------------
1 | class JsonUser {
2 | public constructor() {
3 | }
4 |
5 | Token: string;
6 | User: string;
7 | NonceStr: string;
8 | Timestamp: number;
9 | UID: number;
10 | FES: string;
11 | IP:string;
12 | Port:number;
13 | }
14 |
--------------------------------------------------------------------------------
/EgretWebSocket/src/module/LoginModule.ts:
--------------------------------------------------------------------------------
1 | class LoginModule {
2 |
3 | public Init() {
4 | NetMgr.GetInstance().addEventListener("AuthOk", this.CBAuthOk, this);
5 | }
6 |
7 | public CBAuthOk() {
8 | console.log("AuthOk回调,进入大厅场景");
9 | }
10 |
11 |
12 |
13 |
14 | public static GetInstance(): LoginModule {
15 | if (this.__self == null) {
16 | this.__self = new LoginModule();
17 | }
18 | return this.__self;
19 | }
20 |
21 | private constructor() {}
22 | private static __self: LoginModule;
23 | }
24 |
--------------------------------------------------------------------------------
/EgretWebSocket/src/module/Player/PlayerDataModule.ts:
--------------------------------------------------------------------------------
1 |
2 | class PlayerDataModule{
3 |
4 | public Init() {
5 | NetMgr.GetInstance().addEventListener("SyncPlayerInfo", this.CBSyncPlayerInfo, this);
6 | }
7 |
8 | public CBSyncPlayerInfo( event: NetEvent ) {
9 |
10 | let pb_playerinfo: PB.MsgPlayerInfo = event.msg.rprotobuf(PB.MsgPlayerInfo);
11 |
12 |
13 | console.log("SyncPlayerInfo");
14 | console.log(pb_playerinfo);
15 |
16 |
17 |
18 | }
19 |
20 |
21 | public static GetInstance(): PlayerDataModule {
22 | if (this.__self == null) {
23 | this.__self = new PlayerDataModule();
24 | }
25 | return this.__self;
26 | }
27 |
28 | private constructor() {
29 |
30 | }
31 | private static __self: PlayerDataModule;
32 | }
33 |
34 |
35 |
--------------------------------------------------------------------------------
/EgretWebSocket/src/network/Message.ts:
--------------------------------------------------------------------------------
1 | class Message {
2 |
3 | public name: string;
4 | public buff_msg: egret.ByteArray;
5 |
6 |
7 | public constructor(name = '') {
8 | this.buff_msg = new egret.ByteArray();
9 | this.buff_msg.endian = egret.Endian.LITTLE_ENDIAN;
10 | this.reset(name);
11 | }
12 |
13 | reset( name: string ) {
14 | this.name = name;
15 | this.buff_msg.clear();
16 | this.buff_msg.writeInt(0);
17 | this.buff_msg.writeByte(0);
18 | this.wstring(this.name);
19 | }
20 |
21 | fill( val: egret.ByteArray, offset:number, len: number ) {
22 | this.buff_msg.clear();
23 | this.buff_msg.writeBytes(val, offset, len);
24 |
25 | // read name
26 | this.buff_msg.position = 5;
27 | this.name = this.rstring();
28 | }
29 |
30 | wstring( val: string ){
31 | this.wint32( val.length );
32 | this.buff_msg.writeUTFBytes (val);
33 | }
34 |
35 | wint32( val: number ) {
36 | this.buff_msg.writeInt(val);
37 | }
38 |
39 | wuint32( val: number ) {
40 | this.buff_msg.writeUnsignedInt(val);
41 | }
42 |
43 | wint64( val: (Long | number | string) ){
44 | let long = protobuf.util.LongBits.from( val );
45 | this.wuint32(long.lo);
46 | this.wuint32(long.hi);
47 | }
48 |
49 | wdouble(val: number) {
50 | this.buff_msg.writeDouble(val);
51 | }
52 |
53 | wprotobuf(pb_type, pb_stru) {
54 | let buff_msg = pb_type.encode(pb_stru).finish();
55 | let egret_buffer = new egret.ByteArray(buff_msg);
56 |
57 | this.wint32( egret_buffer.length );
58 | this.buff_msg.writeBytes(egret_buffer, 0, egret_buffer.length);
59 | }
60 |
61 | wjson(val: any){
62 | this.wstring(JSON.stringify(val));
63 | }
64 |
65 | ////////////////////////
66 |
67 | rint32() {
68 | return this.buff_msg.readInt();
69 | }
70 |
71 | ruint32() {
72 | return this.buff_msg.readUnsignedInt();
73 | }
74 |
75 | rdouble(){
76 | return this.buff_msg.readDouble();
77 | }
78 |
79 | rstring(){
80 | let len = this.rint32();
81 | return this.buff_msg.readUTFBytes(len);
82 | }
83 |
84 | rint64(unsigned?: boolean){
85 | let val = new protobuf.util.LongBits(0,0);
86 | val.hi = this.ruint32();
87 | val.lo = this.ruint32();
88 | return val.toLong(unsigned);
89 | }
90 |
91 | rjson(){
92 | let len = this.rint32();
93 | let json_str = this.buff_msg.readUTFBytes(len);
94 | return JSON.parse(json_str);
95 | }
96 |
97 | rprotobuf(msg_type: any) {
98 | let len = this.rint32();
99 | let pb_buffer = new egret.ByteArray();
100 | this.buff_msg.readBytes( pb_buffer, 0, len );
101 | return msg_type.decode(pb_buffer.bytes);
102 | }
103 |
104 |
105 | }
106 |
107 |
--------------------------------------------------------------------------------
/EgretWebSocket/src/network/NetEvent.ts:
--------------------------------------------------------------------------------
1 | class NetEvent extends egret.Event {
2 |
3 | //public static Net: string = "NetEvent";
4 |
5 | public msg: Message;
6 |
7 | public constructor(type: string, bubbles: boolean = false, cancelable: boolean = false) {
8 | super(type, bubbles, cancelable);
9 | }
10 |
11 |
12 | }
--------------------------------------------------------------------------------
/EgretWebSocket/src/network/NetMgr.ts:
--------------------------------------------------------------------------------
1 | // TypeScript file
2 | /**
3 | * 网络管理类
4 | */
5 | class NetMgr extends egret.DisplayObject {
6 |
7 | private socket: egret.WebSocket = new egret.WebSocket();
8 | static net: NetMgr;
9 | private recv_buffer: egret.ByteArray = new egret.ByteArray();
10 | private send_buffer: egret.ByteArray = new egret.ByteArray();
11 | private temp_msg: Message = new Message();
12 | private conn_url: string;
13 |
14 | constructor() {
15 | super();
16 |
17 | }
18 | public static GetInstance(): NetMgr {
19 | if (this.net == null) {
20 | this.net = new NetMgr();
21 |
22 | }
23 | return this.net;
24 | }
25 |
26 | public Connect(serverurl: string): void {
27 | if (this.socket.connected) return;
28 |
29 | this.socket.type = egret.WebSocket.TYPE_BINARY;
30 | this.socket.addEventListener(egret.ProgressEvent.SOCKET_DATA, this.onReceiveMessage, this);
31 | this.socket.addEventListener(egret.Event.CONNECT, this.onSocketOpen, this);
32 | this.socket.addEventListener(egret.IOErrorEvent.IO_ERROR, this.IOError, this);
33 | this.socket.addEventListener(egret.Event.CLOSE, this.Close, this);
34 | this.socket.connectByUrl(serverurl)
35 |
36 | this.conn_url = serverurl;
37 | }
38 |
39 | /**
40 | * 发送消息
41 | */
42 | public SendMsg(msg: Message): void {
43 | try {
44 |
45 | if ( this.socket.connected ){
46 | this.send_buffer.clear();
47 | this.send_buffer.endian = egret.Endian.BIG_ENDIAN;
48 | this.send_buffer.writeInt(msg.buff_msg.length);
49 | this.send_buffer.endian = egret.Endian.LITTLE_ENDIAN;
50 | this.send_buffer.writeBytes(msg.buff_msg);
51 |
52 | this.socket.writeBytes(this.send_buffer, 0, this.send_buffer.length);
53 | this.socket.flush();
54 | }
55 | else{
56 | console.error("网络没有连接");
57 | }
58 |
59 | } catch (e) {
60 | console.error(e);
61 | }
62 | }
63 |
64 | public SendPB( msg_name: string, pb_type:any, pb_stru: any ): void {
65 | this.temp_msg.reset(msg_name);
66 | this.temp_msg.wprotobuf(pb_type, pb_stru);
67 | this.SendMsg(this.temp_msg);
68 | }
69 |
70 | public GetStatus(): boolean {
71 | return this.socket.connected;
72 | }
73 |
74 |
75 |
76 | onReceiveMessage(): void {
77 |
78 | this.socket.readBytes(this.recv_buffer, this.recv_buffer.position);
79 |
80 | if (this.recv_buffer.bytesAvailable > 4) {
81 |
82 | this.recv_buffer.endian = egret.Endian.BIG_ENDIAN;
83 | let msg_len = this.recv_buffer.readInt();
84 | this.recv_buffer.endian = egret.Endian.LITTLE_ENDIAN;
85 |
86 | if (this.recv_buffer.bytesAvailable >= msg_len) {
87 |
88 | let msg = new Message();
89 | msg.fill(this.recv_buffer, this.recv_buffer.position, msg_len);
90 |
91 | this.processReceive(msg);
92 | }
93 | else {
94 | console.log("msg len error");
95 | }
96 |
97 | this.recv_buffer.clear();
98 | }
99 | }
100 |
101 | private processReceive(msg: Message) {
102 | console.log("recv msg : " + msg.name);
103 | let netevent: NetEvent = new NetEvent(msg.name)
104 | netevent.msg = msg;
105 | this.dispatchEvent(netevent);
106 | }
107 |
108 |
109 | Close(): void {
110 | console.log("连接关闭")
111 | }
112 |
113 | onSocketOpen(): void {
114 | console.log("网络连接成功,发送LOGIN。");
115 |
116 | let user: JsonUser = ClientModule.GetInstance().UserInfo;
117 | let pb_login = PB.MsgLogin.create();
118 | pb_login.Version = ClientModule.GetInstance().Version;
119 | pb_login.Channel = ClientModule.GetInstance().Channel;
120 | pb_login.AppName = ClientModule.GetInstance().AppName;
121 | pb_login.User = user.User;
122 | pb_login.NonceStr = user.NonceStr;
123 | pb_login.Token = user.Token;
124 | pb_login.Timestamp = user.Timestamp;
125 | pb_login.UID = user.UID;
126 | pb_login.RoomType = ClientModule.GetInstance().RoomType;
127 |
128 | NetMgr.GetInstance().SendPB( "LOGIN", PB.MsgLogin, pb_login );
129 | }
130 |
131 | IOError(): void {
132 | console.log("网络连接断开")
133 | }
134 |
135 | }
--------------------------------------------------------------------------------
/EgretWebSocket/template/runtime/native_loader.js:
--------------------------------------------------------------------------------
1 | require("launcher/native_require.js");
2 |
3 | egret_native.egtMain = function () {
4 | egret_native.nativeType = "native";
5 |
6 | egret_native.egretInit();
7 | egret_native.egretStart();
8 | };
9 |
--------------------------------------------------------------------------------
/EgretWebSocket/template/runtime/native_require.js:
--------------------------------------------------------------------------------
1 | var manifest = JSON.parse(egret_native.readFileSync("manifest.json"));
2 | var game_file_list = manifest.initial.concat(manifest.game);
3 |
4 | var window = this;
5 |
6 | egret_native.setSearchPaths([""]);
7 |
8 | egret_native.requireFiles = function () {
9 | for (var key in game_file_list) {
10 | var src = game_file_list[key];
11 | require(src);
12 | }
13 | };
14 |
15 | egret_native.egretInit = function () {
16 | if(egret_native.featureEnable) {
17 | //控制一些优化方案是否开启
18 | //Control whether some optimization options are open
19 | var result = egret_native.featureEnable({
20 |
21 | });
22 | }
23 | egret_native.requireFiles();
24 | egret.dom = {};
25 | egret.dom.drawAsCanvas = function () {
26 | };
27 | };
28 |
29 | egret_native.egretStart = function () {
30 | var option = {
31 | //以下为自动修改,请勿修改
32 | //The following is automatically modified, please do not modify
33 | //----auto option start----
34 | entryClassName: "Main",
35 | frameRate: 30,
36 | scaleMode: "fixedWidth",
37 | contentWidth: 640,
38 | contentHeight: 1136,
39 | showPaintRect: false,
40 | showFPS: false,
41 | fpsStyles: "x:0,y:0,size:12,textColor:0xffffff,bgAlpha:0.9",
42 | showLog: false,
43 | logFilter: "",
44 | maxTouches: 2,
45 | textureScaleFactor: 1
46 | //----auto option end----
47 | };
48 |
49 | egret.native.NativePlayer.option = option;
50 | egret.runEgret();
51 | egret_native.Label.createLabel("/system/fonts/DroidSansFallback.ttf", 20, "", 0);
52 | egret_native.EGTView.preSetOffScreenBufferEnable(true);
53 | };
--------------------------------------------------------------------------------
/EgretWebSocket/template/runtime/runtime_loader.js:
--------------------------------------------------------------------------------
1 | require("launcher/native_require.js");
2 |
3 | egret_native.egtMain = function () {
4 | egret_native.nativeType = "runtime";
5 |
6 | egret_native.egretInit();
7 | egret_native.egretStart();
8 | };
--------------------------------------------------------------------------------
/EgretWebSocket/template/web/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Egret
7 |
8 |
9 |
10 |
11 |
12 |
13 |
23 |
24 |
25 |
26 |
37 |
38 |
94 |
95 |
96 |
--------------------------------------------------------------------------------
/EgretWebSocket/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "outDir": "bin-debug",
5 | "experimentalDecorators": true,
6 | "lib": [
7 | "es5",
8 | "dom",
9 | "es2015.promise"
10 | ],
11 | "types": []
12 | },
13 | "include": [
14 | "src",
15 | "libs"
16 | ]
17 | }
--------------------------------------------------------------------------------
/EgretWebSocket/wingProperties.json:
--------------------------------------------------------------------------------
1 | {
2 | "resourcePlugin":{
3 | "configs":[{
4 | "configPath":"resource/default.res.json",
5 | "relativePath":"resource/"
6 | }]
7 | },
8 | "theme":"resource/default.thm.json"
9 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 0xcc
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # BaseService
2 | 微信小游戏服务器,房间及卡牌类游戏服务器。支持websocket及tcp连接,lua编写游戏逻辑,运行于C++服务器,跨平台。C++底层已支持多款线上产品。
3 |
4 | 使用lua编写游戏逻辑,不需要编写C++代码。
5 |
6 |
7 |
8 | ### 服务器分类:
9 | ```
10 | naming_service 名字服务器,用于服务器间互相注册,不对外提供服务。
11 |
12 | player_logic_service 用来均摊逻辑的服务器,游戏逻辑写在这里。
13 |
14 | schedule_service 调度服务器,用来统一协调服务器资源,比如分配房间。
15 |
16 | frontend_service 前端服务器,主要用于处理网络连接,消息转发,也可以缓存一部分热点数据。
17 | ```
18 |
19 | ### 配置:
20 | 每种服务器有与自己名字相同的配置文件,如frontend_service.cfg
21 |
22 | ```
23 | AESAliasName = "fes_0"; // 服务器别名,在运营工具中查看服务器状态时显示这个名字。
24 | SId = 66; // 服务器ID,唯一。
25 |
26 | StartLuaScript = "_FESMain.lua"; // 脚本执行入口
27 |
28 | Paths =
29 | {
30 | "./script/_FES/", // 脚本文件查找路径
31 | };
32 |
33 | ```
34 |
35 |
36 | ###脚本工程:
37 | ```
38 | server\script\DataTable 各种配置文件的目录
39 | server\script\Framework 框架提供的基础工具。
40 | server\script\SharedLib 游戏共享库,与游戏逻辑相关的共享代码在这里。
41 | server\script\_FES 前端服务器代码。
42 | server\script\_PLS 逻辑服务器代码。
43 | server\script\_SCH 调度服务器代码。
44 |
45 | ```
46 |
47 | ### 脚本调用顺序
48 |
49 | ```
50 | 1.服务器启动时读取.cfg配置文件,运行对应的StartLuaScript。
51 | 2.调用其中的 function ServiceInit()
52 | 3.每帧调用 function ServiceUpdate()
53 | 4.程序退出调用 function ServiceRelease()
54 |
55 | ```
56 |
57 |
58 | ### 简单通信
59 |
60 | server\script\_FES\_FESMain.lua
61 |
62 | https://github.com/li9chuan/EgretWebSocket
63 |
64 | ```
65 | function MsgLogin:ctor( Data )
66 |
67 | self._EventRegister = EventRegister.new();
68 |
69 | -- 客户端消息
70 | self._EventRegister:RegisterEvent( "LOGIN", self, self.CBLogin );
71 |
72 | end
73 |
74 | function MsgLogin:CBLogin( sock_id, msg_login )
75 |
76 | nlinfo( msg_login:rint32() );
77 | nlinfo( msg_login:rdouble() );
78 | nlinfo( msg_login:rstring() );
79 | nlinfo( msg_login:rint64() );
80 | nlinfo( msg_login:rint64() );
81 |
82 | -- 将收到的 LOGIN 消息原样发回给客户端。
83 | msg_login:invert();
84 | ClientService:Send( sock_id, msg_login );
85 |
86 | end
87 |
88 | ```
89 |
90 |
--------------------------------------------------------------------------------