Клиент говорит с сервером по нашему протоколу
Раньше клиент умел только показывать меню. Теперь он заходит на сервер,
получает наш мир и рисует его.
Как это устроено:
- Наш сетевой слой (net/rustnotmc/client/net) читает наш протокол и
переводит его пакеты в пакеты игры. Игра остаётся игрой: у неё есть
мир, игрок, сущности и рендер, и все они работают. Не переписывать их
ради того, чтобы нарисовать тот же мир иначе, незачем.
- Пакеты игры, которые не имеют соответствия у нас, не отправляются, а
наоборот: перемещение игрока и ломание блока переводятся в наши.
- Экран входа игры (GuiConnecting) заменён наш: он спрашивает у лаунчера,
кем пришёл игрок, и подставляет это в рукопожатие.
- Соединение качается из тика игры, а не из экрана. Рукопожатие, которое
зависит от того, что экран ещё на экране, ломается alt-tab'ом.
Вход теперь через лаунчер, а не внутри игры:
- Лаунчер уже умеет логинить игрока и отдаёт игре имя, uuid и токен
(--username, --uuid, --accessToken). Это та же роль, что у Yggdrasil в
ванилле, только лаунчер наш.
- Сервер спрашивает лаунчер, один из ли наш этот игрок, и заодно получает
бан-лист. Токен используется один раз и не хранится.
- Свои аккаунты сервера, когда настроен лаунчер, закрыты: сервер с двумя
дверями не имеет дверей. Открыть их можно флагом, но намеренно.
- Если игру запустили без лаунчера, экран всё равно спрашивает имя и
пароль: это путь для своего сервера и для разработки.
Проверено живьём: клиент вошёл по токену лаунчера, сервер спросил
лаунчер, лаунчер сказал "свой", игрок получил мир, 210 чанков пришли и
лежат на диске, рельеф нарисован.
Что чинилось по дороге:
- Minecraft.setIngameFocus() возвращал на главное меню, когда окно
получало фокус. Игрок как раз кликает в окно, чтобы напечатать пароль, и
экран входа исчезал в этот самый момент.
- Ответ лаунчера разбирается, а не ищется подстрокой: {"valid": true} и
{"valid":true} это один и тот же ответ, и сервер, который понимает
только второй, ломает работающий лаунчер.
This commit is contained in:
1 parent
46784aa88f
commit
450bdecc34
10 files changed
+1085
-3
No files matched your search
@@ -0,0 +1,252 @@
|
||||
package net.minecraft.client.multiplayer;
|
||||
|
||||
import com.mojang.authlib.GameProfile;
|
||||
import java.io.IOException;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.GuiButton;
|
||||
import net.minecraft.client.gui.GuiDisconnected;
|
||||
import net.minecraft.client.gui.GuiScreen;
|
||||
import net.minecraft.client.gui.GuiTextField;
|
||||
import net.minecraft.util.text.TextComponentTranslation;
|
||||
import net.rustnotmc.client.gui.RsxPasswordField;
|
||||
import net.rustnotmc.client.net.RsxNetworkManager;
|
||||
import net.rustnotmc.client.net.RsxWorldBridge;
|
||||
|
||||
/**
|
||||
* The screen that gets the player into a server.
|
||||
*
|
||||
* The launcher is where accounts live, so the launcher signs the player in and
|
||||
* hands the game a token. This screen then has nothing to ask: it takes the
|
||||
* token out of the session the launcher built and offers it to the server.
|
||||
*
|
||||
* When the game was started without a launcher there is no session and
|
||||
* somebody has to say who they are, so the screen asks for a name and a
|
||||
* password. That is the way in for a server of our own and the way in for
|
||||
* development; a server with a launcher in front of it does not accept it.
|
||||
*
|
||||
* This replaces the game's own connecting screen, which is where the player
|
||||
* already is when they press "join server", so the flow stays the one they
|
||||
* know.
|
||||
*/
|
||||
public class GuiConnecting extends GuiScreen {
|
||||
|
||||
/** What the launcher leaves in the session when nobody signed in. */
|
||||
private static final String NO_TOKEN = "0";
|
||||
|
||||
private final GuiScreen previousGuiScreen;
|
||||
private final String host;
|
||||
private final int port;
|
||||
|
||||
private GuiTextField accountField;
|
||||
private RsxPasswordField passwordField;
|
||||
private RsxNetworkManager networkManager;
|
||||
private volatile String status = "";
|
||||
|
||||
/** The launcher's session, if the game was started by the launcher. */
|
||||
private String launcherAccount;
|
||||
private String launcherUuid;
|
||||
private String launcherToken;
|
||||
|
||||
public GuiConnecting(GuiScreen guiscreen, Minecraft minecraft, ServerData serverdata) {
|
||||
this.mc = minecraft;
|
||||
this.previousGuiScreen = guiscreen;
|
||||
ServerAddress serveraddress = ServerAddress.fromString(serverdata.serverIP);
|
||||
minecraft.loadWorld((WorldClient) null);
|
||||
minecraft.setServerData(serverdata);
|
||||
this.host = serveraddress.getIP();
|
||||
this.port = serveraddress.getPort();
|
||||
}
|
||||
|
||||
public GuiConnecting(GuiScreen guiscreen, Minecraft minecraft, String s, int i) {
|
||||
this.mc = minecraft;
|
||||
this.previousGuiScreen = guiscreen;
|
||||
minecraft.loadWorld((WorldClient) null);
|
||||
this.host = s;
|
||||
this.port = i;
|
||||
}
|
||||
|
||||
public void initGui() {
|
||||
this.buttonList.clear();
|
||||
|
||||
this.launcherAccount = sessionValue(this.mc, 0);
|
||||
this.launcherUuid = sessionValue(this.mc, 1);
|
||||
this.launcherToken = sessionValue(this.mc, 2);
|
||||
|
||||
this.accountField = new GuiTextField(0, this.fontRenderer, this.width / 2 - 100,
|
||||
this.height / 4 + 20, 200, 20);
|
||||
this.accountField.setMaxStringLength(32);
|
||||
this.accountField.setText(this.launcherAccount == null
|
||||
? this.mc.getSession().getProfile().getName() : this.launcherAccount);
|
||||
|
||||
this.passwordField = new RsxPasswordField(1, this.fontRenderer, this.width / 2 - 100,
|
||||
this.height / 4 + 50, 200, 20);
|
||||
this.passwordField.setMaxStringLength(128);
|
||||
|
||||
// two buttons side by side, and they must not lie on top of each other:
|
||||
// the plain constructor makes a button two hundred wide
|
||||
this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 90,
|
||||
98, 20, "Connect"));
|
||||
this.buttonList.add(new GuiButton(1, this.width / 2 + 2, this.height / 4 + 90,
|
||||
98, 20, "Cancel"));
|
||||
|
||||
if (this.hasLauncherSession()) {
|
||||
// the launcher already signed the player in, so there is nothing to
|
||||
// ask for and nothing to wait for
|
||||
this.passwordField.setFocused(true);
|
||||
this.start();
|
||||
} else {
|
||||
this.passwordField.setFocused(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void updateScreen() {
|
||||
if (this.networkManager == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.networkManager.isChannelOpen()) {
|
||||
this.networkManager.processReceivedPackets();
|
||||
return;
|
||||
}
|
||||
|
||||
String reason = this.networkManager.failure();
|
||||
this.mc.displayGuiScreen(new GuiDisconnected(this.previousGuiScreen, "connect.failed",
|
||||
new TextComponentTranslation("disconnect.genericReason", new Object[]{
|
||||
reason == null ? "the connection was closed" : reason})));
|
||||
}
|
||||
|
||||
protected void keyTyped(char c0, int i) {
|
||||
if (c0 == '\r' || c0 == '\n') {
|
||||
this.start();
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.accountField.isFocused()) {
|
||||
this.accountField.textboxKeyTyped(c0, i);
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.passwordField.isFocused()) {
|
||||
this.passwordField.textboxKeyTyped(c0, i);
|
||||
}
|
||||
}
|
||||
|
||||
public void mouseClicked(int mouseX, int mouseY, int mouseButton) {
|
||||
super.mouseClicked(mouseX, mouseY, mouseButton);
|
||||
this.accountField.mouseClicked(mouseX, mouseY, mouseButton);
|
||||
this.passwordField.mouseClicked(mouseX, mouseY, mouseButton);
|
||||
}
|
||||
|
||||
protected void actionPerformed(GuiButton guibutton) {
|
||||
if (guibutton.id == 0) {
|
||||
this.start();
|
||||
} else if (guibutton.id == 1) {
|
||||
this.mc.displayGuiScreen(this.previousGuiScreen);
|
||||
}
|
||||
}
|
||||
|
||||
public void drawScreen(int i, int j, float f) {
|
||||
this.drawDefaultBackground();
|
||||
this.drawCenteredString(this.fontRenderer, "RustNotMC", this.width / 2,
|
||||
this.height / 4 - 20, 16777215);
|
||||
|
||||
if (this.hasLauncherSession()) {
|
||||
this.drawCenteredString(this.fontRenderer, "signed in as " + this.launcherAccount,
|
||||
this.width / 2, this.height / 4 + 10, 8421504);
|
||||
} else {
|
||||
this.drawString(this.fontRenderer, "Account", this.width / 2 - 100,
|
||||
this.height / 4 + 10, 8421504);
|
||||
this.accountField.drawTextBox();
|
||||
this.drawString(this.fontRenderer, "Password", this.width / 2 - 100,
|
||||
this.height / 4 + 40, 8421504);
|
||||
this.passwordField.drawTextBox();
|
||||
}
|
||||
|
||||
if (!this.status.isEmpty()) {
|
||||
this.drawCenteredString(this.fontRenderer, this.status, this.width / 2,
|
||||
this.height / 4 + 120, 16777215);
|
||||
}
|
||||
|
||||
super.drawScreen(i, j, f);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the connection.
|
||||
*
|
||||
* The socket is opened on a thread of its own, because a server that does
|
||||
* not answer must not freeze the game.
|
||||
*/
|
||||
private void start() {
|
||||
if (this.networkManager != null) {
|
||||
return;
|
||||
}
|
||||
|
||||
String account;
|
||||
String token = null;
|
||||
String uuid = null;
|
||||
char[] password = new char[0];
|
||||
|
||||
if (this.hasLauncherSession()) {
|
||||
account = this.launcherAccount;
|
||||
token = this.launcherToken;
|
||||
uuid = this.launcherUuid;
|
||||
} else {
|
||||
account = this.accountField.getText().trim();
|
||||
password = this.passwordField.getText().toCharArray();
|
||||
if (account.isEmpty()) {
|
||||
this.status = "an account name is needed";
|
||||
return;
|
||||
}
|
||||
if (password.length == 0) {
|
||||
this.status = "a password is needed";
|
||||
return;
|
||||
}
|
||||
this.passwordField.setText("");
|
||||
}
|
||||
|
||||
this.status = "connecting to " + this.host + ":" + this.port;
|
||||
System.out.println("[rsx] connecting to " + this.host + ":" + this.port + " as " + account);
|
||||
|
||||
final RsxNetworkManager manager = new RsxNetworkManager(this.mc, this.previousGuiScreen,
|
||||
new GameProfile(RsxWorldBridge.uuidFor(account), account),
|
||||
account, password, token, uuid);
|
||||
this.networkManager = manager;
|
||||
|
||||
(new Thread("Rsx Connect") {
|
||||
public void run() {
|
||||
try {
|
||||
manager.connect(GuiConnecting.this.host, GuiConnecting.this.port);
|
||||
} catch (IOException e) {
|
||||
manager.fail("could not connect: " + e);
|
||||
}
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
/** True when the launcher gave the game a session to use. */
|
||||
private boolean hasLauncherSession() {
|
||||
return this.launcherToken != null && !this.launcherToken.isEmpty()
|
||||
&& !NO_TOKEN.equals(this.launcherToken);
|
||||
}
|
||||
|
||||
/**
|
||||
* A piece of the session the launcher built.
|
||||
*
|
||||
* Zero is the name, one is the identity, two is the token.
|
||||
*/
|
||||
private static String sessionValue(Minecraft minecraft, int which) {
|
||||
if (minecraft == null || minecraft.getSession() == null) {
|
||||
return null;
|
||||
}
|
||||
switch (which) {
|
||||
case 0:
|
||||
return minecraft.getSession().getUsername();
|
||||
case 1:
|
||||
return minecraft.getSession().getPlayerID();
|
||||
case 2:
|
||||
return minecraft.getSession().getToken();
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user