I want to consume the following audio stream with Java - https://playoutonestreaming.com/proxy/bylr?mp=/stream.
Main goal is pretty simple - I want to create a service, which would allow me to have 300-400 active connections (e. g. active listeners) at the moment. The problem appears when I try to make a connection with OkHttp.
Here is the code I have:
@Slf4j
@RequiredArgsConstructor
class ListenStream implements Runnable {
private static final String STREAM_URL = "https://playoutonestreaming.com/proxy/bylr?mp=/stream";
private final OkHttpClient client;
private final int id;
@Override
public void run() {
Clip clip;
try {
log.info("[TASK-{}] - Connecting to the stream...", id);
Request request = new Request.Builder()
.url(STREAM_URL)
.get()
.build();
Response response = client.newCall(request).execute();
assert response.body() != null;
InputStream is = new ByteArrayInputStream(response.body().bytes());
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(is);
clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.loop(Clip.LOOP_CONTINUOUSLY);
} catch (IOException e) {
log.info("Finished listening to the stream");
} catch (LineUnavailableException | UnsupportedAudioFileException e) {
log.error("Failed to process audio stream");
e.printStackTrace();
}
}
}
public class RadioMain {
public static void main(String[] args) throws InterruptedException {
OkHttpClient client = new OkHttpClient.Builder()
.callTimeout(120, TimeUnit.SECONDS)
.connectTimeout(120, TimeUnit.SECONDS)
.readTimeout(120, TimeUnit.SECONDS)
.writeTimeout(120, TimeUnit.SECONDS)
.followRedirects(true)
.followSslRedirects(true)
.build();
ExecutorService service = Executors.newFixedThreadPool(300);
List<Runnable> tasks = IntStream.range(1, 301)
.mapToObj(number -> new ListenStream(client, number))
.collect(Collectors.toList());
tasks.forEach(service::submit);
service.awaitTermination(120, TimeUnit.SECONDS);
service.shutdown();
}
}
With the following approach, I have to set the timeout for OkHttpClient, and then make a request using it. But, as soon as the timeout appears, I'm getting an InterruptedIOException: socket closed
, and I need to create a new task.
Is there a correct way to consume an audio stream with OkHttp?
A call timeout will fail the request after that length of time, so remove that setting or define it as 0.
https://square.github.io/okhttp/4.x/okhttp/okhttp3/-ok-http-client/-builder/call-timeout/
Sets the default timeout for complete calls. A value of 0 means no timeout, otherwise values must be between 1 and Integer.MAX_VALUE when converted to milliseconds.
The call timeout spans the entire call: resolving DNS, connecting, writing the request body, server processing, and reading the response body. If the call requires redirects or retries all must complete within one timeout period.
The default value is 0 which imposes no timeout.