【发布时间】:2023-03-29 21:29:03
【问题描述】:
我写了这个简单的代码:
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 有没有办法向主类的主函数发送信号,或者有人知道如何实现这个?
【问题讨论】:
-
我不知道你问的是否可行,但我会留下一个建议(可能不是一个好的建议)。在无限循环中创建一个额外的线程来检查“信号”。然后你向那个额外的线程发送“信号”,当它收到信号时,它会创建一个新线程来发送用户输入。当它结束发送时,继续做你正在做的另一件事,而循环将永远运行。
-
感谢您的回答@HugoSousa,但问题是当额外线程创建一个新线程来发送用户输入时,该线程中的扫描仪和主线程中的扫描仪之间会发生竞争功能
-
A
static扫描仪不能解决这个问题吗? -
我没想过我会试试这个
-
请同时发布客户端代码。
标签: java multithreading chat