Merge pull request 'Add cli arguments, nick support and add data.db to .gitignore.' (#1) from bedohswe/crab:master into master

Reviewed-on: #1
This commit is contained in:
pixtaded 2025-01-10 15:42:36 +00:00
commit 44d11f18d6
4 changed files with 67 additions and 9 deletions

2
.gitignore vendored
View File

@ -1,3 +1,5 @@
data.db
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar

View File

@ -7,9 +7,43 @@ import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
chooseMode(scanner);
scanner.close();
if (args.length == 0) {
Scanner scanner = new Scanner(System.in);
chooseMode(scanner);
scanner.close();
return;
}
switch (args[0]) {
case "help" -> {
System.out.println("crab help - print this message.");
System.out.println("crab client <ip> <port> [nick] - connect to a server.");
System.out.println("crab server <port> - start a server.");
}
case "client" -> {
CrabClient client;
try {
client = new CrabClient(args[1], Integer.parseInt(args[2]), args.length == 4 ? args[3] : null);
} catch (NumberFormatException e) {
System.err.println("Port is not a number.");
return;
}
client.run();
}
case "server" -> {
CrabServer server;
try {
server = new CrabServer(Integer.parseInt(args[1]));
} catch (NumberFormatException e) {
System.err.println("Port is not a number.");
return;
}
server.run();
}
default -> {
System.err.println("Unknown argument");
return;
}
}
}
private static void chooseMode(Scanner scanner) {

View File

@ -17,15 +17,26 @@ public class CrabClient implements Crab {
private PrintWriter out;
private BufferedReader in;
private int lastBufferLength = 0;
private String nickname;
public CrabClient() {
this.nickname = "";
}
public CrabClient(String serverAddress, int port, String nickname) {
this.serverAddress = serverAddress;
this.port = port;
if (nickname != null)
this.nickname = "<" + nickname + "> ";
else
this.nickname = "";
}
@Override
public void run() {
try {
setup();
if (this.serverAddress == null)
setup();
connect();
communicate();
} catch (IOException e) {
@ -54,6 +65,11 @@ public class CrabClient implements Crab {
System.out.println("Enter a correct port number: ");
}
}
System.out.print("Enter your nickname (leave empty for no nickname): ");
nickname = scanner.nextLine();
if (nickname != "")
nickname = "<" + nickname + "> ";
}
private void connect() throws IOException {
@ -77,7 +93,7 @@ public class CrabClient implements Crab {
break;
}
if (!message.isEmpty()) sendPacket(MESSAGE, message);
if (!message.isEmpty()) sendPacket(MESSAGE, this.nickname + message);
}
}

View File

@ -18,10 +18,16 @@ public class CrabServer implements Crab {
this.db = new Database("data.db");
}
public CrabServer(int port) {
this.db = new Database("data.db");
this.port = port;
}
@Override
public void run() {
try {
setup();
if (this.port == 0)
setup();
listen();
} catch (IOException e) {
if (!isStopped) System.err.println("Error starting server: " + e.getMessage());