Skip to content

Commit

Permalink
feat: implement Joining server socket
Browse files Browse the repository at this point in the history
  • Loading branch information
LapisBerry committed May 22, 2024
1 parent 17994ba commit 6356d5b
Show file tree
Hide file tree
Showing 7 changed files with 122 additions and 27 deletions.
18 changes: 18 additions & 0 deletions src/main/java/com/lapisberry/Main.java
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
package com.lapisberry;

import com.lapisberry.gui.scenes.JoinScene;
import com.lapisberry.net.Client;
import com.lapisberry.net.Server;
import com.lapisberry.utils.exceptions.ConnectionRefusedException;
import javafx.application.Application;
import javafx.scene.image.Image;
import javafx.stage.Stage;

public class Main extends Application {
private static Stage primaryStage;
private static Server server;
private static Client client;

// methods
public static void main(String[] args) {
Expand All @@ -23,6 +26,7 @@ public void start(Stage stage) {
primaryStage.setScene(new JoinScene());
primaryStage.setOnCloseRequest(event -> {
closeServer();
closeClient();
System.exit(0);
});

Expand All @@ -41,7 +45,21 @@ public static void closeServer() {
if (server != null) server.close();
}

public static void createClient(String host) {
client = new Client(host);
new Thread(client, "Client thread").start();
}

public static void closeClient() {
if (client != null) client.close();
}

// Getters Setters
public static Stage getPrimaryStage() {
return primaryStage;
}

public static Client getClient() {
return client;
}
}
70 changes: 57 additions & 13 deletions src/main/java/com/lapisberry/gui/scenes/JoinScene.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,14 @@

import com.lapisberry.Main;
import com.lapisberry.gui.MediaController;
import com.lapisberry.utils.exceptions.ConnectionRefusedException;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
Expand All @@ -18,20 +23,22 @@
import static com.lapisberry.gui.FontPreloader.*;

public class JoinScene extends Scene {
private static final Title title = new Title("MaKillMai");
private static final InputField username = new InputField("username");
private static final InputField ipAddress = new InputField("ip-address");
private static final JoinButton joinButton = new JoinButton("Join");
private static final CreateServerButton createServerButton = new CreateServerButton();
private static final Container container = new Container(title, username, ipAddress, joinButton, createServerButton);

private static final AlertContainer alertContainer = new AlertContainer();

public JoinScene() {
super(new StackPane(new Container()), 1280, 720);
super(new StackPane(alertContainer, container), 1280, 720);
}

private static class Container extends VBox {
private Container() {
super();
Title title = new Title("MaKillMai");
InputField username = new InputField("username");
InputField ipAddress = new InputField("ip-address");
JoinButton joinButton = new JoinButton("Join");
CreateServerButton createServerButton = new CreateServerButton();

getChildren().addAll(title, username, ipAddress, joinButton, createServerButton);
private Container(Node... children) {
super(children);
setMaxWidth(400);
setMaxHeight(200);
setAlignment(Pos.CENTER);
Expand All @@ -51,7 +58,7 @@ private static class InputField extends TextField {
private InputField(String promptText) {
super();
setPromptText(promptText);
setFont(Font.loadFont(Inter_ExtraLight, 40));
setFont(Font.loadFont(Inter_Light, 40));
setBackground(new Background(new BackgroundFill(Color.valueOf("D9D9D9"), new CornerRadii(10), null)));
setMaxWidth(400);
setMinHeight(80);
Expand Down Expand Up @@ -79,14 +86,22 @@ private JoinButton(String text) {
setOnMousePressed(e -> setBackground(pressedBackground));
setOnMouseReleased(e -> setBackground(hoverBackground));
setOnAction(e -> {
Main.getPrimaryStage().setScene(new LobbyScene());
MediaController.playMediaOnce(MediaController.buttonClickSound);
if (username.getText().isBlank()) {
alertContainer.alert("Username can't be blank.");
return;
}
try {
Main.createClient(ipAddress.getText());
Main.getPrimaryStage().setScene(new LobbyScene());
} catch (ConnectionRefusedException ex) {
alertContainer.alert("Connection refused.");
}
});
}
}

private static class CreateServerButton extends Button {

private CreateServerButton() {
super("Create Server");
AtomicBoolean isServerCreated = new AtomicBoolean(false);
Expand Down Expand Up @@ -116,6 +131,7 @@ private CreateServerButton() {
setOnMousePressed(e -> setBackground(pressedBackground.get()));
setOnMouseReleased(e -> setBackground(hoverBackground.get()));
setOnAction(e -> {
MediaController.playMediaOnce(MediaController.buttonClickSound);
if (isServerCreated.get()) {
Main.closeServer();
setText("Create Server");
Expand All @@ -133,4 +149,32 @@ private CreateServerButton() {
});
}
}

private static class AlertContainer extends BorderPane {
private static final Label alertLabel = new Label();
static {
alertLabel.setFont(Font.loadFont(Inter_Regular, 18));
alertLabel.setTextFill(Color.WHITE);
alertLabel.setBackground(new Background(new BackgroundFill(Color.valueOf("FF0000"), new CornerRadii(10), null)));
alertLabel.setPadding(new Insets(10));
alertLabel.setAlignment(Pos.CENTER);
}

private void alert(final String alertMessage) {
alertLabel.setText(alertMessage);
new Thread(() -> {
Platform.runLater(() -> setRight(alertLabel));
try {
Thread.sleep(3000);
} catch (InterruptedException ignored) {
}
Platform.runLater(() -> setRight(null));
}, "alert thread").start();
}

private AlertContainer() {
super();
setPadding(new Insets(10));
}
}
}
23 changes: 18 additions & 5 deletions src/main/java/com/lapisberry/net/Client.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package com.lapisberry.net;

import com.lapisberry.net.packets.ClientPacket;
import com.lapisberry.net.packets.ServerPacket;
import com.lapisberry.utils.Config;
import com.lapisberry.utils.exceptions.ConnectionRefusedException;

import java.io.IOException;
import java.io.ObjectInputStream;
Expand All @@ -20,7 +23,8 @@ public Client(final String host) {
this.outputStream = new ObjectOutputStream(socket.getOutputStream());
this.inputStream = new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
throw new RuntimeException("Client cannot be created.");
System.out.println("Client cannot be created.");
throw new ConnectionRefusedException("Connection refused.");
}
}

Expand All @@ -33,23 +37,32 @@ public void run() {
private void startListeningServerPacket() {
while (!socket.isClosed()) {
try {
Object packet = inputStream.readObject();
ServerPacket packet = (ServerPacket) inputStream.readObject();
System.out.println("Packet received from server: " + packet);
} catch (IOException e) {
System.out.println("Server disconnected.");
break;
} catch (ClassNotFoundException e) {
} catch (ClassNotFoundException | ClassCastException e) {
System.out.println("Packet from server cannot be read.");
}
}
}

private void sendPacketToServer(Object packet) {
private void sendPacketToServer(ClientPacket packet) {
try {
outputStream.writeObject(packet);
outputStream.flush();
} catch (IOException e) {
System.out.println("Packet cannot be sent to server.");
}
}

public void close() {
try {
socket.close();
outputStream.close();
inputStream.close();
} catch (IOException e) {
System.out.println("Client cannot be closed.");
}
}
}
10 changes: 5 additions & 5 deletions src/main/java/com/lapisberry/net/ClientHandler.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.lapisberry.net;

import java.io.EOFException;
import com.lapisberry.net.packets.ClientPacket;
import com.lapisberry.net.packets.ServerPacket;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
Expand All @@ -13,7 +15,6 @@ public class ClientHandler implements Runnable {
private ObjectOutputStream outputStream;
private ObjectInputStream inputStream;


// Constructors
public ClientHandler(Server server, Socket socket) {
this.server = server;
Expand All @@ -26,7 +27,6 @@ public ClientHandler(Server server, Socket socket) {
}
}


// Methods
@Override
public void run() {
Expand All @@ -36,7 +36,7 @@ public void run() {
private void startListeningClientPacket() {
while (!socket.isClosed()) {
try {
Object packet = inputStream.readObject();
ClientPacket packet = (ClientPacket) inputStream.readObject();
server.processPacketFromClient(this, packet);
} catch (IOException e) {
System.out.println("Client disconnected: " + socket.getInetAddress().getHostAddress());
Expand All @@ -47,7 +47,7 @@ private void startListeningClientPacket() {
}
}

public void sendPacketToClient(Object packet) {
public void sendPacketToClient(ServerPacket packet) {
try {
outputStream.writeObject(packet);
outputStream.flush();
Expand Down
8 changes: 5 additions & 3 deletions src/main/java/com/lapisberry/net/Server.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.lapisberry.net;

import com.lapisberry.net.packets.ClientPacket;
import com.lapisberry.net.packets.ServerPacket;
import com.lapisberry.utils.Config;

import java.io.IOException;
Expand Down Expand Up @@ -35,20 +37,20 @@ private void startAcceptingClients() {
Socket socket = serverSocket.accept();
ClientHandler clientHandler = new ClientHandler(this, socket);
clientHandlers.add(clientHandler);
new Thread(clientHandler).start();

System.out.println("Client connected: " + socket.getInetAddress().getHostAddress());
new Thread(clientHandler).start();
} catch (IOException e) {
System.out.println("Server cannot accept client anymore. Server is closed.");
}
}
}

public void processPacketFromClient(ClientHandler sender, Object packet) {
public void processPacketFromClient(ClientHandler sender, ClientPacket packet) {
System.out.println("Processing packet from " + sender.getSocket().getInetAddress().getHostAddress() + ": " + packet);
}

private void sendPacketToAllClients(Object packet) {
private void sendPacketToAllClients(ServerPacket packet) {
for (ClientHandler clientHandler : clientHandlers) {
clientHandler.sendPacketToClient(packet);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
*/
public class JoinRequestPacket extends ClientPacket implements Serializable {
@Serial
private static final long serialVersionUID = -3120924882895484001L;
private static final long serialVersionUID = 8969814260705260127L;
// Fields
private final String username;

Expand All @@ -17,6 +17,12 @@ public JoinRequestPacket(String username) {
this.username = username;
}

// Methods
@Override
public String toString() {
return "JoinRequestPacket{username=" + username + "}";
}

// Getters
public String getUsername() {
return username;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.lapisberry.utils.exceptions;

import java.io.Serial;

public class ConnectionRefusedException extends RuntimeException {
@Serial
private static final long serialVersionUID = 5965444325760963522L;

public ConnectionRefusedException(String message) {
super(message);
}
}

0 comments on commit 6356d5b

Please sign in to comment.