0

I wrote this simple code :

class main{
public static void main(String []a)throws UnknownHostException,IOException{
    Scanner sc = new Scanner(System.in);
    int choice;
    ServerSocket ss = new ServerSocket(60000,1,InetAddress.getLocalHost());
    Thread t = new Thread(new Conversation(ss));
    t.start();
    while(true){// I think i need to set a better condition here
        do{
            System.out.println("Hello user choose a number between 0 and 2");
        }
        while(!sc.hasNextInt());
        choice = sc.nextInt();
        if(choice >2 || choice < 0)
            choice = 0;
        switch(choice){
            case 0:
            //print some stuff
            break;
            case 1:
            //print other stuff
            break;
            case 2:
            //print new stuff
            break;
            default:
            break;
        }
    }
}

}

And heres the code of the class Conversation :

public class Conversation implements Runnable {
ServerSocket ss;
Socket client;
boolean connected;
Conversation(ServerSocket cli){
    this.ss= cli;
    client = null;
    connected = false;
}
void connected(){
    this.connected = true;
}
void disconnected(){
    this.connected = false;
}
@Override
public void run() {
    // TODO Auto-generated method stub
    while(true) {
        PrintWriter pw = null;
        if(!this.connected){
            try {
                client = ss.accept();
                pw =new PrintWriter(client.getOutputStream(),true);
                this.connected();
            } catch (IOException e) {
                System.err.println("Accept failed.");
                System.err.println(e);
                System.exit(1);
            }
            BufferedReader in = null;
            PrintWriter out = null;
            try {
                in = new BufferedReader(new InputStreamReader(
                    client.getInputStream()));
                out = new PrintWriter(client.getOutputStream(), true);
            } catch (IOException e) {
                System.err.println(e);
                return;
            }

            String msg;
            try {
                while ((msg = in.readLine()) != null) {
                    if(msg.equals("CLO") || msg.equals("clo")){// if a CLO message is sent the conversation ends
                        client.close();
                        in.close();
                        out.close();
                        pw.close();
                        this.disconnected();
                        break;
                    }
                    else{
                        System.out.println("Client says: " + msg.substring(7));
                    }
                }
            } catch (IOException e) {
                System.err.println(e);
            }
        }
    }
}

}

Basically all it does is to wait for a user input and then prints something according to what he typed. The problem I'm facing is: I want that when someone connects to the ServerSocket ss in the thread t(so the value of connected is true)I want the main function to stop whatever it is doing and to just send the user input into the OutputStream of the socket client(so in other words starting a chat when someone connects to the ServerSocket). But i don't know how to do so I'm new in Threading and networks in Java , is there a way for the thread T to send a signal to the main function of the main class or does anybody have an idea of how to achieve this ?

user3129482
  • 109
  • 1
  • 7
  • I don't know if what you asked is possible but I'll leave a suggestion (probably not a good one). Create an extra thread in a infinite loop cheking for the "signal". Then you send to that extra thread the "signal" and when it gets the signal, it creates a new thread to send the user input. When it ends sending, keep doing the other thing you were doing, while the loop is running forever. – Hugo Sousa Apr 18 '14 at 22:33
  • Thank you for your answer @HugoSousa but A problem is that when the extra thread creates a new thread to send the user input there will be a competition between the scanner in that thread and the scanner in the main function – user3129482 Apr 18 '14 at 22:48
  • A `static` Scanner wouldn't solve that problem? – Hugo Sousa Apr 18 '14 at 22:50
  • I haven't thought about that i'll try this – user3129482 Apr 18 '14 at 22:53
  • Please post the client side code also. – Braj Apr 18 '14 at 22:57

1 Answers1

0

I have already posted some samples code in the same context. Please have a look at below samples and try to follow each and every step to understand it. Read inline comments carefully.

please let me know if there is any confusion.

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
  • There could be multiple clients but an application can only have one conversation at one time. so I don't think I need a multithreading TCP chat program. My only problem is that the behaviour of the application if totally different according to if there is a connection of not No connection: I need to print answers to user input. A connection has been established: Stop everything and start chatting – user3129482 Apr 18 '14 at 23:27
  • That's what I have done so far I haven't code the Client part yet since I'm stuck in the loop in the main function of the main class and I won't be able to start chatting – user3129482 Apr 18 '14 at 23:42
  • Look at your posted code. what is `ConversationServeur`. what is `pw`. Its not in compiled state. – Braj Apr 18 '14 at 23:47
  • Sorry for this error i've edited my post. ps is the PrintWriter got from the OutputStream of the socket client – user3129482 Apr 18 '14 at 23:58
  • What about this line `Thread t = new Thread(new Conversation());`. you don't have default constructor. – Braj Apr 19 '14 at 00:01
  • Post edited again sorry for those errors in fact my problem is bigger than that, I tried to make it simplier by creating this two classes so users won't have to read 4 or 5 different classes – user3129482 Apr 19 '14 at 00:09