Home > database >  Trying to make class A wait for trigger from an object that class A instantiates
Trying to make class A wait for trigger from an object that class A instantiates

Time:11-15

I'm currently trying to make a program in which 2 identical programs send messages to each other through Java sockets. The base idea is working and the program can connect to another one. The issue is that I want to update something in the GUI if the program receives a connection from another one.

A have class Controller which creates an instance of class Client. Client handles connections and has a thread running to accept any connection. Controller controls the GUI

public class Client extends Thread {

Socket socket;
ServerSocket serverSocket;
boolean incomingConnected = false;
boolean outgoingConnected = false;
int port;

//Makes a server socket for first connection
public Client() {
    try {
        //Creates port to listen on
        port = (int)(Math.random() * 5000)   1000;
        //Creates socket
        serverSocket = new ServerSocket(port);

    } catch (Exception e) { e.printStackTrace(); }
}

//This method is to automate 2 PCs connecting, only one must connect rather then both to each other
@Override
public void run() {
    try {
        //Makes sure its not already connected
        if (!incomingConnected) {
            //Listens for connection
            serverSocket.accept();

/*
CODE SENT TO CONTROLLER CLASS TO UPDATE GUI
*/

            incomingConnected = true;
            //Connects server socket to other PC
            if(!outgoingConnected) {
                connect(serverSocket.getInetAddress(), serverSocket.getLocalPort());
            }
        }

    } catch (Exception e) { e.printStackTrace(); }
}

//Connects the socket to another computer, is true if it connects
public void connect(InetAddress address, int port) {

    outgoingConnected = false;

    try {
        socket = new Socket(address, port);
        outgoingConnected = true;
    } catch (Exception e) { e.printStackTrace(); }
}
}

Maybe its possible to set up a thread in Controller that waits for a signal but I'm unsure how to do that.

CodePudding user response:

 public class Client extends Thread {

...
final Controller controller;

//Makes a server socket for first connection
public Client(Controler controller) {
    this.controller = controller;
    ...
}

//This method is to automate 2 PCs connecting, only one must connect rather then both to each other
@Override
public void run() {
    try {
        //Makes sure its not already connected
        if (!incomingConnected) {
            //Listens for connection
            serverSocket.accept();

            controller.sendMessage("client accepted a new connection);

           ...
    }
}

class Controller {
    public Controller() {
        new Client(this);
    }
}
  • Related