Here is the code:
Server:
public class Server {
public static void main(String[] args) {
Connection conn = new Connection();
new Thread(conn).start();
}
private static class Connection implements Runnable {
Queue<MovementCommand> commandQueue = new LinkedList<>();
@Override
public void run() {
try (ServerSocket serverSocket = new ServerSocket(5005)) {
Socket socket = serverSocket.accept();
listener(socket);
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void listener(Socket socket) {
commandQueue.add(new MovementCommand("Point-0001", "NOP"));
commandQueue.add(new MovementCommand("Point-0002", "NOP"));
commandQueue.add(new MovementCommand("Point-0004", "NOP"));
commandQueue.add(new MovementCommand("Point-0008", "NOP"));
commandQueue.add(new MovementCommand("Point-0011", "NOP"));
boolean alive = true;
MovementCommand curCommand;
while (alive) {
try {
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
curCommand = this.commandQueue.poll();
if (curCommand != null) {
outputStream.writeUTF(curCommand.getPoint() + " - " + curCommand.getOperation());
String data = inputStream.readUTF();
System.out.println("New reported position: " + data);
}
} catch (IOException ex) {
ex.printStackTrace();
alive = false;
}
}
}
}
}
Client:
public class Client {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 5005)) {
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
boolean alive = true;
while (alive) {
try {
String data = inputStream.readUTF();
System.out.println("Incoming data: " + data);
Thread.sleep(2000);
outputStream.writeUTF(data.substring(0, 10));
outputStream.flush();
} catch (Exception ex) {
ex.printStackTrace();
alive = false;
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Thank you in advance !!