I need help in my server. I successfully play songs after receiving certain messages but when i receive stop it stops the song but crashes the server. I thank you in advance for your help
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");
}
}
}
}
This is what my console looks like after executing this code
IP: Timskie-PC/192.168.1.118 Port: 7777
Server started. Listening to the port 7777
rock1
stop
but still doesnt stop the song
Try this:
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();
}
EDIT
Notice that Clip clip4 = null;
is not a member variable. It is declared inside the while loop. Each time the loop iterates, it is being redeclared. If you declare it as a Class level "member variable" you will get a different result.