0

我正在尝试创建一个服务器来发送基于另一个类的计算结果的消息。

我的问题是,由于计算结果来自另一个类,我如何让服务器暂停直到结果准备好,我应该如何将结果传递给我的服务器类并发送结果?

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();
    }
}
4

3 回答 3

0

利用

    Thread.sleep(30000); // Milli secs - 30 secs -- Put your sleep time
sendMessage(myServerSend);
于 2013-02-14T07:33:01.147 回答
0

你有几个选择来实现这一点:

Thread1-为您的计算创建一个并调用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之间的共享对象上使用servercalculation

3-使用semaphore初始化的对象0acquire在您的服务器类中调用以等待并release在您完成计算后调用,请参阅我的答案作为示例

于 2013-02-14T07:48:39.447 回答
0

如果没有关于您尝试过的内容以及为什么放弃尝试过的内容的更具体信息,我在这里看到了几个选项。

  1. 直接调用其他类并等待结果准备好。如果计算时间太长,这可能不是一个好主意,但如果不是,这是最简单的方法。

  2. 您可以应用轮询并让服务器休眠一段时间,以免在等待答案时耗尽资源。

  3. 通过等待和通知方法使用同步对象和并发。一些有用的链接:1 2 3

于 2013-02-14T07:37:38.507 回答