0

I've been messing around with sockets and I've tried to create a server with multi threading in order to get the requests from clients. Each request has it's special functionality, so a client can get a response from another client using the server. Three types of clients are sending requests type A with socket number 2000, type B with socket number 3000 and type C with socket number 4000.But I've run into a scenario that I couldn't solve Software caused connection abort: socket write error. This error occurred when trying to send request from client B with socket 3000 to Server then transmitting the request from Server to client C with socket 4000, the client C gather the necessary data and send it back to Server in order to finally reach it's destination with the client B. All of the data that are sent between clients are exchanged using ObjectOutputStream and ObjectInputStream

Kindly, suggests the correct way to send requests and get responses from a client to another one using server.

Here's my code :

Server code:

public class Saca {
public static final int portAvion = 2000;
public static final int portRadar = 3000;
public static final int portControlleur = 4000;
public static ServerSocket serveurPortAvion;
public static ServerSocket serveurPortRadar;
public static ServerSocket serveurPortControlleur;

public static Socket socketAvion;
public static Socket socketRadar;
public static Socket socketControlleur;
public static void main(String []args) throws IOException, ClassNotFoundException{
    new Saca().demarerServeur();
}

public void demarerServeur() throws IOException, ClassNotFoundException{
    serveurPortAvion = new ServerSocket(portAvion);
    serveurPortRadar = new ServerSocket(portRadar);
    serveurPortControlleur = new ServerSocket(portControlleur);
    System.out.println("Le serveur est lance");
    while(true){
        try {
            socketAvion = serveurPortAvion.accept();
            SacaThread sacaThreadAvion = new SacaThread(socketAvion);
            sacaThreadAvion.start();

            socketRadar = serveurPortRadar.accept();
            SacaThread sacaThreadRadar = new SacaThread(socketRadar);
            sacaThreadRadar.start();

            socketControlleur = serveurPortControlleur.accept();
            SacaThread sacaThreadControlleur = new SacaThread(socketControlleur);
            sacaThreadControlleur.start();
        } catch (Exception ex) {
            System.out.println("Message d'erreur : " + ex.getMessage());
        }
    }    
}

Server Multi Threading code:

public class SacaThread extends Thread{
Socket socket = null;
SacaThread(Socket socket){
    this.socket = socket;
}

public void run(){
    try {
        ObjetInter objetInter = null;
        ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
        //ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
        while ((objetInter = (ObjetInter)objectInputStream.readObject()) != null) {
            switch (socket.getLocalPort()) {
                case 2000:
                    //LES TACHES D'AVION
                    System.out.println(objetInter.getMessage());
                    if(objetInter.getAction().toLowerCase().equals("envoi_donnees") && Saca.socketRadar.isConnected()){
                        //ServerSocket socketServerRadar = new ServerSocket(portRadar);
                        //Socket socketRadar = socketServerRadar.accept();
                        ObjectOutputStream objectOutputStreamRadar = new ObjectOutputStream(Saca.socketRadar.getOutputStream());
                        objectOutputStreamRadar.writeObject(objetInter);
                        objectOutputStreamRadar.close();
                    }
                    break;
                case 3000:
                    //LES TACHES DU RADAR
                    //System.out.println(objetInter.toString());
                    if(objetInter.getAction().toLowerCase().equals("avoir_liste") && Saca.socketControlleur.isConnected()){
                        ObjectOutputStream objectOutputStreamControllleur = new ObjectOutputStream(Saca.socketControlleur.getOutputStream());
                        objectOutputStreamControllleur.writeObject(objetInter);
                        objectOutputStreamControllleur.close();
                    }
                    break;
                case 4000:
                    //LES TACHES DU CONTROLLEUR
                    //System.out.println(objetInter.toString());
                    if (objetInter.getAction().toLowerCase().equals("avoir_liste") && Saca.socketRadar.isConnected()) {
                        ObjectOutputStream objectOutputStreamRadar = new ObjectOutputStream(Saca.socketRadar.getOutputStream());
                        objectOutputStreamRadar.writeObject(objetInter);

                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException e) {
                        }
                        objectOutputStreamRadar.close();
                    }

                    break;
            }

        }
        objectInputStream.close();
        socket.close();

    } catch (IOException ex) {
        //System.out.println("Radar exception : " + ex.getMessage());
    } catch (ClassNotFoundException ex) {
        //System.out.println("Radar exception : " + ex.getMessage());
    }

}

Class B

public class Radar {

public int PAUSE = 1000;
public int tempsMiseAJour = 10000;
public int tempsPasse = 0;
private static ArrayList<String> listAvion = new ArrayList<String>();
Socket socket;
ObjectOutputStream objectOutputStream;
ObjectInputStream objectInputStream;

boolean ouvrir_communication() {
    boolean conxOuverte = false;
    try {
        socket = new Socket("localhost", Saca.portRadar);
        conxOuverte = true;
    } catch (IOException ex) {
        //System.out.println(ex.getStackTrace());
        return conxOuverte;
    }
    return conxOuverte;
}

void fermer_communication() {

    try {
        if (socket.isConnected()) {
            socket.close();
        }
    } catch (IOException ex) {
    }
}

public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException {
    Radar r = new Radar();
    r.lancerRadar();
}

void actionSurListe() throws ClassNotFoundException {
    try {
        ObjetInter objetInter = null;
        objectInputStream = new ObjectInputStream(socket.getInputStream());
        //objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
        while ((objetInter = (ObjetInter) objectInputStream.readObject()) != null) {
            switch (objetInter.getAction().toLowerCase()) {
                case "envoi_donnees":
                    ...
                    break;
                case "avoir_liste":
                    envoie_listeAvion();
                    break;
            }

        }
        objectInputStream.close();
    } catch (IOException ex) {

    }
}


void lancerRadar() throws ClassNotFoundException {
    while (true) {

        try {
            ouvrir_communication();
            Thread.sleep(PAUSE);
            actionSurListe();
            tempsPasse += PAUSE;
            if (tempsPasse == tempsMiseAJour) {
                afficherListAvion();
                tempsPasse = 0;
            }
            fermer_communication();
        } catch (InterruptedException ex) {
        }
    }
}

void envoie_listeAvion() throws IOException {
    if (socket.isConnected()) {
        try {
            objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            objectOutputStream.writeObject(new ObjetInter("Radar", "envoi_liste", listAvion.toString()));
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
            }
            objectOutputStream.flush();
            objectOutputStream.close();
        } catch (IOException ex) {
            System.out.println("Exception " + ex.getMessage());
            objectOutputStream.close();
        }
    } else {
        System.out.println("Socket non connecte !");
    }
}

Class C

public class Controlleur implements Runnable {
static int selectionMenu = -1;
Socket socket;
ObjectOutputStream objectOutputStream;
ObjectInputStream objectInputStream;
private Avion avion;
static volatile boolean keepRunning = true;
static Controlleur test ;
static Thread t;

boolean ouvrir_communication() {
    boolean conxOuverte = false;
    try {
        socket = new Socket("localhost", Saca.portControlleur);
        conxOuverte = true;
    } catch (IOException ex) {
        return conxOuverte;
    }
    return conxOuverte;
}

void fermer_communication() {

    try {
        if (socket.isConnected()) {
            socket.close();
        }
    } catch (IOException ex) {
    }
}


void demandeListAvion(){
    try {
        ObjetInter objetInter = null;
        objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
        objectOutputStream.writeObject(new ObjetInter("Controlleur", "avoir_liste", ""));
        objectOutputStream.flush();
    } catch (IOException ex) {

    }
}

void afficherListAvion() throws ClassNotFoundException, IOException{
    try {
        ObjetInter objetInter = null;
        objectInputStream = new ObjectInputStream(socket.getInputStream());

        while ((objetInter = (ObjetInter) objectInputStream.readObject()) != null) {
                switch (objetInter.getAction().toLowerCase()) {
                    case "envoi_liste":
                        objetInter.getMessage().toString();
                        break;
                }
        }
        //objectInputStream.close();

    } catch (IOException ex) {

    }
}

public void run() {
    System.out.println("Starting to loop.");
    while (keepRunning) {
        ouvrir_communication();
        System.out.println("Running loop...");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            switch(selectionMenu){
                case 0:
                    //System.out.println("0 est selectionné");


                    {
                        try {
                            Thread.sleep(3000);
                            demandeListAvion();
                            Thread.sleep(3000);
                            afficherListAvion();
                        } catch (ClassNotFoundException ex) {
                            Logger.getLogger(Controlleur.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (IOException ex) {
                            Logger.getLogger(Controlleur.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (InterruptedException ex) {
                        }

                    }
                    break;
            }

        }
        fermer_communication();
    }
    afficherMenu();
    System.out.println("Done looping.");
}

public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException {
    test = new Controlleur();

    afficherMenu();


}

static void afficherMenu(){
    selectionMenu = -1;
    keepRunning = true;
    t = new Thread(test);
    t.start();

    System.out.println("Choisir du menu : ");
    System.out.println("--------------------------------");
    System.out.println("0 - Quitter Menu");
    System.out.println("1 - Afficher liste des avions");
    System.out.println("2 - Attacher pilote à une avion");
    Scanner s = new Scanner(System.in);
    while ((selectionMenu = s.nextInt()) != 0);

    test.keepRunning = false;
    t.interrupt();  // cancel current sleep.
}
  • 1
    Welcome to Stack Overflow! I would imagine that 99% of this code is not relevant to your problem. Please create a [**Minimal**, Complete and Verifiable Example](http://stackoverflow.com/help/mcve) that demonstrates your issue. – Joe C Jul 16 '17 at 19:57
  • My apologize EJP and JoeC I didn't explain my code. First, in the server code section I've created the server socket and then in the While I've accepted the incoming connections of clients for the three types of clients "Avion", "Radar", "Controlleur", these clients have different behavior in the Server Thread section. – Edgard CHAMOUN Jul 18 '17 at 04:11
  • Second, in the mutli thread server code I've created a class that extends Thread, a constructor that takes the clients socket. Inside the Run method, it listens to the inputs of clients, according to the socket client and the action that is written inside the object objetInter, I take the action to call the Output stream of a client and send back response to it. – Edgard CHAMOUN Jul 18 '17 at 04:11
  • In Class B which indicates the "Radar" class, I've created a main that contains the instance of the class and launch the method "lancerRadar()" to open the socket of the radar and launch the method of "actionSurListe()" that reads the input stream from the server side and takes the actions according to the objetInter.getAction(). – Edgard CHAMOUN Jul 18 '17 at 04:16
  • In Class C, I've created the method "afficherMenu()" to display the menu where the user can choose a request to send it to server. The issue comes here, the user chooses "0", the method "demanderListeAvion()" writes on the outputstream of the socket controlleur, the server receives the request in the section of Server multi threading code > Run() > switch case 4000, then we writes the request to the "Radar" client using the outputstream of the socket "Radar", the "Radar" receives the request in the method "actionSurListe()" using inputstream of socket "Radar". – Edgard CHAMOUN Jul 18 '17 at 04:24
  • According to the action sent from the server, the request will call the method "envoie_listeAvion()", where the errors comes in at line **objectOutputStream.writeObject(new ObjetInter("Radar", "envoi_liste", listAvion.toString()));**, is there any problem to rewrite the response on the same socket that have received the request ? – Edgard CHAMOUN Jul 18 '17 at 04:30
  • Or is there anything wrong concerning the idea of sending request and response using the logic of Client( demand request ) > Server ( manages which client should get the request) > Client (chosen client by server receives the request) & (send back response to server) >Server ( get response and chooses the client that requested that response) > Client ( receives the response of his request) ? Please any help – Edgard CHAMOUN Jul 18 '17 at 04:32
  • The fact that it took 6 long comments to explain your code just demonstrates my point that there's far too much of it in your question. Please reduce the amount of code to no more than 20 lines that can demonstrate your problem. – Joe C Jul 18 '17 at 05:09

0 Answers0