我正在尝试创建一个服务器来发送一条消息,该消息基于另一个类的计算结果。
我的问题是,由于计算结果来自另一个类,如何让服务器暂停直到结果准备好,如何将结果传递给我的服务器类并发送结果?
public class MyServer {
ServerSocket providerSocket;
Socket connection = null;
static ObjectOutputStream out;
ObjectInputStream in;
String message;
public static String myServerSend;
BufferedReader data = new BufferedReader(data);
MyServer() {}
void run() {
try {
providerSocket = new ServerSocket(2013, 10);
System.out.println("Waiting for connection");
connection = providerSocket.accept();
out = new ObjectOutputStream(connection.getOutputStream());
out.flush();
in = new ObjectInputStream(connection.getInputStream());
do {
try {
message = (String) in.readObject();
System.out.println("server receive>" + message);
// HERE IS MY QUESTION
// myServerSend is the result from other class,
//How can I pause the server here till myServerSend is ready???????
sendMessage(myServerSend);
} catch (ClassNotFoundException classnot) {
System.err.println("Data received in unknown format");
}
} while (!message.equals("bye"));
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
//write msg into ObjectOutputStream
public static void sendMessage(String msg) {
try {
out.writeObject(msg);
out.flush();
System.out.println("server send>" + msg);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
答案 0 :(得分:0)
使用
Thread.sleep(30000); // Milli secs - 30 secs -- Put your sleep time
sendMessage(myServerSend);
答案 1 :(得分:0)
如果没有关于您尝试过的内容的更多具体信息以及您放弃尝试的内容的原因,我会在此处看到几个选项。
答案 2 :(得分:0)
你没有多少选择来实现这个目标:
1-为您的计算创建Thread
并致电join
让您的服务器等待线程完成
Thread thread = new Thread() {
public void run(){
// Call your calculation class
}
}
thread.start();
thread.join(); // surround with try and catch
// or you can use to timeout if the calculation took long
// thread.join(MAX_TIME_MILLIS);
sendMessage(myServerSend);
2-在wait/notify
和server
班级之间的共享对象上使用calculation
3-使用semaphore
初始化的0
对象并在服务器类中调用acquire
等待并在完成计算后致电release
,请参阅{{3}例如