我写了这个简单的代码:
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;
}
}
}
}
并且继承了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);
}
}
}
}
}
基本上它只是等待用户输入,然后根据他输入的内容打印一些内容。 我面临的问题是: 我希望当有人连接到线程t中的ServerSocket ss时(所以connected的值为true)我希望main函数停止它正在做的事情并且只是将用户输入发送到套接字客户端的OutputStream(所以换句话说,当有人连接到ServerSocket时开始聊天。 但我不知道如何做到这一点我是新的线程和Java网络,有没有办法让线程T向主类的主要功能发送信号,或者有人有一个如何实现这一目标的想法?
答案 0 :(得分:0)
我已在相同的上下文中发布了一些示例代码。请查看以下示例,并尝试按照每个步骤来理解它。仔细阅读内联评论。
如果有任何混淆,请告诉我。