-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathquick_match.js
219 lines (206 loc) · 6.67 KB
/
quick_match.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
/**
* Manages the communication with the quick match server.
*
* Major parts of fetch API code is copied from https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
*/
'use strict';
import { serverURL } from './quick_match_server_url.js';
import { createRoom, joinRoom } from '../data_channel/data_channel.js';
import { blockedIPList } from '../block_other_players/blocked_ip_list.js';
import { MATCH_GROUP } from './match_group.js';
import {
printCommunicationCount,
printQuickMatchState,
printQuickMatchLog,
printFailedToConnectToQuickMatchServer,
printNumberOfSuccessfulQuickMatches,
} from '../ui_online.js';
let roomIdToCreate = null;
let matchGroup = null;
let communicationCount = null;
const MESSAGE_TO_SERVER = {
initial: 'initial',
roomCreated: 'roomCreated',
quickMatchSuccess: 'quickMatchSuccess',
withFriendSuccess: 'withFriendSuccess',
cancel: 'cancel',
};
export const MESSAGE_TO_CLIENT = {
createRoom: 'createRoom',
keepWait: 'keepWait', // keep sending wait packet
connectToPeer: 'connectToPeer',
connectToPeerAfterAWhile: 'connectToPeerAfterAWhile',
waitPeerConnection: 'waitPeerConnection', // wait the peer to connect to you
abandoned: 'abandoned',
};
/**
* Start request/response with quick match server
* @param {string} roomIdToCreateIfNeeded
* @param {string} matchGroupForQuickMatch
*/
export function startQuickMatch(
roomIdToCreateIfNeeded,
matchGroupForQuickMatch
) {
roomIdToCreate = roomIdToCreateIfNeeded;
matchGroup = matchGroupForQuickMatch;
communicationCount = 0;
postData(
serverURL,
objectToSendToServer(
MESSAGE_TO_SERVER.initial,
roomIdToCreate,
matchGroup,
blockedIPList.createHashedIPArray()
)
).then(callback);
}
/**
* In quick match, the room creator send this quick match success message if data channel is opened.
*/
export function sendQuickMatchSuccessMessageToServer() {
console.log('Send quick match success message to server');
postData(
serverURL,
objectToSendToServer(
MESSAGE_TO_SERVER.quickMatchSuccess,
roomIdToCreate,
matchGroup
)
);
}
/**
* In "with friend", the room creator send this packet if data channel is opened.
*/
export function sendWithFriendSuccessMessageToServer() {
console.log('Send with friend success message to server');
postData(
serverURL,
objectToSendToServer(MESSAGE_TO_SERVER.withFriendSuccess, roomIdToCreate)
);
}
/**
* In quick match, the room creator send this quick match cancel packet if they want to cancel quick match i.e. want to stop waiting.
*/
export function sendCancelQuickMatchMessageToServer() {
console.log('Send cancel quick match message to server');
postData(
serverURL,
objectToSendToServer(MESSAGE_TO_SERVER.cancel, roomIdToCreate, matchGroup)
);
}
// Example POST method implementation:
async function postData(url = '', data = {}) {
try {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'default', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data), // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
} catch (e) {
printQuickMatchLog(e);
printFailedToConnectToQuickMatchServer();
}
}
const callback = (data) => {
// JSON data parsed by `response.json()` call
if (data.numOfSuccess !== null) {
const numOfSuccess = data.numOfSuccess;
printNumberOfSuccessfulQuickMatches(
numOfSuccess.withinLast24hours,
numOfSuccess.withinLast1hour,
numOfSuccess.withinLast10minutes
);
}
switch (data.message) {
case MESSAGE_TO_CLIENT.createRoom:
console.log('Create room!');
createRoom(roomIdToCreate).then(() =>
postData(
serverURL,
objectToSendToServer(
MESSAGE_TO_SERVER.roomCreated,
roomIdToCreate,
matchGroup
)
).then(callback)
);
break;
case MESSAGE_TO_CLIENT.keepWait:
console.log('Keep wait!');
window.setTimeout(() => {
postData(
serverURL,
objectToSendToServer(
MESSAGE_TO_SERVER.roomCreated,
roomIdToCreate,
matchGroup
)
).then(callback);
}, 1000);
break;
case MESSAGE_TO_CLIENT.waitPeerConnection:
console.log('Wait peer connection!');
// If the following line is executed after data channel is opened,
// peer hashed ip can be staged too late to enable blocking this peer button,
// which checked if peer hashed ip is staged already.
// But, since the blocking this peer button is rendered after ping test
// which takes about 5 seconds, it will be almost never happened.
blockedIPList.stagePeerHashedIP(data.hashedPeerIP);
break;
case MESSAGE_TO_CLIENT.connectToPeerAfterAWhile:
console.log('Connect To Peer after 3 seconds...');
window.setTimeout(() => {
console.log('Connect To Peer!');
printQuickMatchState(MESSAGE_TO_CLIENT.connectToPeer);
blockedIPList.stagePeerHashedIP(data.hashedPeerIP);
joinRoom(data.roomId);
}, 3000);
break;
case MESSAGE_TO_CLIENT.connectToPeer:
console.log('Connect To Peer!');
blockedIPList.stagePeerHashedIP(data.hashedPeerIP);
joinRoom(data.roomId);
break;
case MESSAGE_TO_CLIENT.abandoned:
console.log('room id abandoned.. please retry quick match.');
break;
case MESSAGE_TO_CLIENT.cancelAccepted:
console.log('quick match cancel accepted');
// TODO: do something
break;
}
communicationCount++;
printCommunicationCount(communicationCount);
printQuickMatchState(data.message);
};
/**
* Create an object to send to server by json
* @param {string} message
* @param {string} roomIdToCreate
* @param {string[]} blockedHashedIPs
* @param {string} matchGroup
*/
function objectToSendToServer(
message,
roomIdToCreate,
matchGroup = MATCH_GROUP.GLOBAL,
blockedHashedIPs = []
) {
return {
message: message,
roomId: roomIdToCreate,
matchGroup: matchGroup,
blockedHashedIPs: blockedHashedIPs,
};
}