Shrink code in the ConnectionHandlers
This commit is contained in:
committed by
Leonardo Brandenberger
parent
46b0e4386a
commit
5022974427
@@ -1,5 +1,10 @@
|
||||
package ch.zhaw.pm2.multichat.protocol;
|
||||
|
||||
import java.io.EOFException;
|
||||
import java.io.IOException;
|
||||
import java.net.SocketException;
|
||||
import java.util.Scanner;
|
||||
|
||||
public abstract class ConnectionHandler {
|
||||
private NetworkHandler.NetworkConnection<String> connection;
|
||||
|
||||
@@ -44,4 +49,47 @@ public abstract class ConnectionHandler {
|
||||
protected void setConnection(NetworkHandler.NetworkConnection<String> connection) {
|
||||
this.connection = connection;
|
||||
}
|
||||
|
||||
protected void processData(Scanner scanner, StringBuilder sender, StringBuilder reciever, StringBuilder type, StringBuilder payload) throws ChatProtocolException {
|
||||
// parse data content
|
||||
if (scanner.hasNextLine()) {
|
||||
sender.append(scanner.nextLine());
|
||||
} else {
|
||||
throw new ChatProtocolException("No Sender found");
|
||||
}
|
||||
if (scanner.hasNextLine()) {
|
||||
reciever.append(scanner.nextLine());
|
||||
} else {
|
||||
throw new ChatProtocolException("No Reciever found");
|
||||
}
|
||||
if (scanner.hasNextLine()) {
|
||||
type.append(scanner.nextLine());
|
||||
} else {
|
||||
throw new ChatProtocolException("No Type found");
|
||||
}
|
||||
if (scanner.hasNextLine()) {
|
||||
payload.append(scanner.nextLine());
|
||||
}
|
||||
}
|
||||
|
||||
protected void sendData(String sender, String receiver, String type, String payload) {
|
||||
if (connection.isAvailable()) {
|
||||
new StringBuilder();
|
||||
String data = new StringBuilder()
|
||||
.append(sender+"\n")
|
||||
.append(receiver+"\n")
|
||||
.append(type+"\n")
|
||||
.append(payload+"\n")
|
||||
.toString();
|
||||
try {
|
||||
getConnection().send(data);
|
||||
} catch (SocketException e) {
|
||||
System.err.println("Connection closed: " + e.getMessage());
|
||||
} catch (EOFException e) {
|
||||
System.out.println("Connection terminated by remote");
|
||||
} catch(IOException e) {
|
||||
System.err.println("Communication error: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user