I'm trying to implement the MAVLink protocol in Java. After testing that I can read and write messages properly I would like to create a Connection class that handles the information process, however, the structure I'm developing doesn't look really nice, so I'm here to look for better ways to implement a Connection class that can handle both TCP and UDP connections.
First of all, I have a reading thread (ReadConnection
) and a writing thread (WriteConnection
). Each of those have the subclasses: ReadTCP
, ReadUDP
, WriteTCP
and WriteUDP
. In an ideal world, I would like the ReadConnection
and WriteConnection
run()
methods to be the same so I don't have to implement a different thread loop for each type of connection (which in my head sounds clearer), but because the behaviour and Objects that are used for each connection are different this seems impossible.
I thought that if I could cast the ReadTCP
subclass to the parent ReadConnection
I would be able to only have one type of ReadConnection
inside the Connection class but casting deletes the properties of the different types of connections.
In the end, I would like to know how should I structure this Connection
class and their subclasses in a way that presents the code clearly and is easy to use.
This is the current state of the Connection
class:
public class Connection extends Thread
{
static ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
private static Lock readLock = rwLock.readLock();
private static Lock writeLock = rwLock.writeLock();
private ReadUDP readUDP;
private WriteUDP writeUDP;
private ReadTCP readTCP;
private WriteTCP writeTCP;
protected static ArrayList<InetAddress> addresses = new ArrayList<>();
public Connection(ConnectionBuilder builder)
{
this.readUDP = builder.readUDP;
this.writeUDP = builder.writeUDP;
this.readTCP = builder.readTCP;
this.writeTCP = builder.writeTCP;
}
public static class ConnectionBuilder
{
private ReadUDP readUDP;
private WriteUDP writeUDP;
private ReadTCP readTCP;
private WriteTCP writeTCP;
public ConnectionBuilder udp(int port)
{
this.readUDP = new ReadUDP(readLock, writeLock, addresses);
this.writeUDP = new WriteUDP();
return this;
}
public ConnectionBuilder tcp(int port)
{
this.readTCP = new ReadTCP();
this.writeTCP = new WriteTCP();
return this;
}
public Connection build()
{
return new Connection(this);
}
}
public void startConnection()
{
if(this.readUDP != null)
{
this.readUDP.start();
}
if(this.writeUDP != null)
{
this.writeUDP.start();
}
if(this.readTCP != null)
{
this.readTCP.start();
}
if(this.writeTCP != null)
{
this.writeTCP.start();
}
}
}