0

我的服务器需要帮助。我在收到某些消息后成功播放歌曲,但是当我收到 stop 时它会停止歌曲但服务器崩溃。我提前感谢您的帮助

    public class server
{
    private static final int PORT = 7777;

    private static ServerSocket serverSocket;
    private static Socket clientSocket;
    private static InputStreamReader inputStreamReader;
    private static BufferedReader bufferedReader;
    private static String message;


    @SuppressWarnings("unused")
    private String filename;  
    private static  Clip clip4;
    static Player player; 

    public server(String filename) {  
        this.filename = filename;  


    }
    public static void main(String[] args) throws Exception

    {


        try
        {
            serverSocket = new ServerSocket(PORT, 0, InetAddress.getLocalHost());

            System.out.println("IP:  " + serverSocket.getInetAddress() + "  Port:  " +  serverSocket.getLocalPort());

        } catch (IOException e)
        {
            System.out.println("Could not listen on port: 7777");
        }

        System.out.println("Server started. Listening to the port 7777");

        while (true)
        {

            try
            {
                clientSocket = serverSocket.accept();
                inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
                bufferedReader = new BufferedReader(inputStreamReader); 
                message = bufferedReader.readLine();


                System.out.println(message);{
                clip4 = null;
     if (message.equals("rock1")) {

                    AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File("D:/Andrd/Music/TheAll-AmericanRejects-Swing,Swing.wav"));
                      clip4 = AudioSystem.getClip();
                      clip4.open(inputStream);
                      clip4.start(); 

                } else if (message.equals("stop") && clip4 = null && clip4.isRunning()){
                     clip4.stop();
                 }
 }


                inputStreamReader.close();
                clientSocket.close();


            }catch (IOException ex)
            {
                System.out.println("Problem in message reading");
            }


        } 
        }

}

这是执行此代码后我的控制台的样子

 IP:  Timskie-PC/192.168.1.118  Port:  7777
    Server started. Listening to the port 7777
    rock1
    stop

但仍然没有停止这首歌

4

1 回答 1

0

尝试这个:

Clip clip4 = null; // Make this a member variable.
...
if (message.equals("rock1")) {
  AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File("D:/Andrd/Music/TheAll-AmericanRejects-Swing,Swing.wav"));
  clip4 = AudioSystem.getClip();
  clip4.open(inputStream);
  clip4.start();
} else if (message.equals("stop") && clip4 != null && clip4.isRunning())
  clip4.stop();
}

编辑

请注意,这Clip clip4 = null;不是成员变量。它在 while 循环中声明。每次循环迭代时,都会重新声明它。如果您将其声明为类级别的“成员变量”,您将得到不同的结果。

于 2013-10-16T21:37:59.683 回答