Skip to content

Commit

Permalink
feat: Added graceful shutdown on device disconnected
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrielmjr committed Sep 22, 2024
1 parent 058d315 commit f09245f
Show file tree
Hide file tree
Showing 9 changed files with 82 additions and 66 deletions.
8 changes: 8 additions & 0 deletions .idea/inspectionProfiles/Project_Default.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions pom.xml
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.mjrt.terminal.localchat</groupId>
<artifactId>terminal-local-chat</artifactId>
<version>1.0-SNAPSHOT</version>
<version>1.0</version>
<packaging>jar</packaging>

<properties>
Expand Down
36 changes: 21 additions & 15 deletions src/main/java/com/mjrt/terminal/localchat/Messenger.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@
import com.mjrt.terminal.localchat.util.DateFormatter;
import lombok.Setter;

import java.io.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Date;
import java.util.Scanner;

import static com.mjrt.terminal.localchat.util.ThreadUtils.threadPools;

public class Messenger {
protected Socket socket;
protected ObjectMapper objectMapper;
Expand All @@ -23,26 +27,28 @@ protected void initializeAttributes() {
}

protected void bindMessageObtainer() {
new Thread(() -> {
threadPools.execute(() -> {
while (!Thread.currentThread().isInterrupted()) {
Message message = null;
try {
while (true) {
var message = obtainMessage();
System.out.printf("%s[%s]: %s%n", message.getFrom(), DateFormatter.fullFormat(message.getSentDate()), message.getMessage());
}
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
message = obtainMessage();
System.out.println(message.getFrom() + "[" + DateFormatter.fullFormat(message.getSentDate()) + "]: " + message.getMessage());
} catch (Exception e) {
System.err.println("Device disconnected");
System.exit(0);
}
}).start();
}
});
}

private Message obtainMessage() throws IOException {
private Message obtainMessage() throws Exception {
var dataInputStream = new DataInputStream(socket.getInputStream());
return objectMapper.readValue(dataInputStream.readUTF(), Message.class);
}

protected void bindMessageSender() throws IOException {
while (true) {
try {
protected void bindMessageSender() {
try {
while (true) {
var messageLabel = scanner.nextLine();
var message = new Message(
thisUsersNickname,
Expand All @@ -53,9 +59,9 @@ protected void bindMessageSender() throws IOException {
dataOutputStream.writeUTF(objectMapper.writeValueAsString(message));
dataOutputStream.flush();
socket.getOutputStream().flush();
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
} catch (IOException e) {
System.err.println("Error when sending message: " + e.getMessage());
}
}
}
36 changes: 14 additions & 22 deletions src/main/java/com/mjrt/terminal/localchat/Options.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,20 @@ private Options() {
objectMapper = new ObjectMapper();
}

public static Options getInstance() {
if (instance == null)
instance = new Options();
return instance;
}

public void process() {
printMessageL("To use the chat your devices must have wifi.");
printMessage("Enter your username/nickname: ");
System.out.println("To use the chat your devices must have wifi.");
System.out.print("Enter your username/nickname: ");
nickname = scanner.nextLine();
printMessageL("\nType 1 to be the server (Turn on hotspot).");
printMessageL("Type 2 to be the client (Turn on wifi).");
System.out.println("\nType 1 to be the server (Turn on hotspot).");
System.out.println("Type 2 to be the client (Turn on wifi).");
System.out.print(">>> ");
switch(readInt()) {
switch (readInt()) {
case 1:
startAsServer();
break;
Expand All @@ -43,7 +49,7 @@ public void process() {
}

private void startAsServer() {
printMessage("Enter the port to listen: ");
System.out.print("Enter the port to listen: ");
port = readInt();
try {
server.setThisUsersNickname(nickname);
Expand All @@ -54,9 +60,9 @@ private void startAsServer() {
}

private void startAsClient() {
printMessage("Enter the ip address: ");
System.out.print("Enter the ip address: ");
String ipAddress = readString();
printMessage("Enter the listened port: ");
System.out.print("Enter the listened port: ");
port = readInt();
try {
client.setThisUsersNickname(nickname);
Expand All @@ -66,25 +72,11 @@ private void startAsClient() {
}
}

public static void printMessage(String message) {
System.out.print(message);
}

public static void printMessageL(String message) {
System.out.println(message);
}

public String readString() {
return scanner.next();
}

private int readInt() {
return scanner.nextInt();
}

public static Options getInstance() {
if (instance == null)
instance = new Options();
return instance;
}
}
20 changes: 10 additions & 10 deletions src/main/java/com/mjrt/terminal/localchat/localclient/Client.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,24 @@
import com.mjrt.terminal.localchat.Connection;
import com.mjrt.terminal.localchat.Messenger;

import static com.mjrt.terminal.localchat.Options.printMessageL;

public class Client extends Messenger {
private static Client instance;

private Client() {}

public void connect(String ipAddress, int port) throws Exception {
initializeAttributes();
socket = Connection.connectAsClient(ipAddress, port);
printMessageL("Connected");
bindMessageObtainer();
bindMessageSender();
private Client() {
}

public static Client getInstance() {
if (instance == null)
instance = new Client();
return instance;
}

public void connect(String ipAddress, int port) throws Exception {
initializeAttributes();
socket = Connection.connectAsClient(ipAddress, port);
System.out.println("Connected");
bindMessageObtainer();
bindMessageSender();
System.out.println("Disconnected");
}
}
27 changes: 14 additions & 13 deletions src/main/java/com/mjrt/terminal/localchat/localserver/Server.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,28 @@
import com.mjrt.terminal.localchat.Messenger;
import com.mjrt.terminal.localchat.util.IpManager;

import java.io.IOException;

import static com.mjrt.terminal.localchat.Options.printMessageL;

public class Server extends Messenger {
private static Server instance;

private Server() {}

public void createConnection(int port) throws IOException {
initializeAttributes();
var serverSocket = Connection.createConnection(port);
printMessageL("Serving in ip: " + IpManager.getInetAddress() + ", port: " + port + "\n");
socket = serverSocket.accept();
bindMessageObtainer();
bindMessageSender();
private Server() {
}

public static Server getInstance() {
if (instance == null)
instance = new Server();
return instance;
}

public void createConnection(int port) throws Exception {
initializeAttributes();
var serverSocket = Connection.createConnection(port);
System.out.println("Serving in ip: " + IpManager.getInetAddress() + ", port: " + port + "\n");
while (true) {
socket = serverSocket.accept();
System.out.println("New device connected");
bindMessageObtainer();
bindMessageSender();
System.out.println("User disconnected");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@ public class DateFormatter {
public static @NotNull String fullFormat(Date date) {
return new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault()).format(date);
}
}
}
4 changes: 2 additions & 2 deletions src/main/java/com/mjrt/terminal/localchat/util/IpManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
public class IpManager {
public static @Nullable String getInetAddress() {
try {
for (var en= NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
for (var en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
var networkInterface = en.nextElement();
if (networkInterface.getName().contains("wlan") || networkInterface.getName().contains("ap")) {
for (var enumInetAddresses = networkInterface.getInetAddresses();enumInetAddresses.hasMoreElements();) {
for (var enumInetAddresses = networkInterface.getInetAddresses(); enumInetAddresses.hasMoreElements(); ) {
var inetAddress = enumInetAddresses.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress.getAddress().length == 4)
return inetAddress.getHostAddress();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.mjrt.terminal.localchat.util;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadUtils {
public static final int NUMBER_OF_POOLS = 1;
public static final ExecutorService threadPools = Executors.newFixedThreadPool(NUMBER_OF_POOLS);
}

0 comments on commit f09245f

Please sign in to comment.