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 ?