Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sending a byte array in pieces. #28

Closed
1 of 2 tasks
germanattanasio opened this issue Jan 14, 2016 · 5 comments
Closed
1 of 2 tasks

Sending a byte array in pieces. #28

germanattanasio opened this issue Jan 14, 2016 · 5 comments

Comments

@germanattanasio
Copy link

I'm trying to use the library to send an InputStream as byte[].

  • If I read and send the entire InputStream(~600kb) everything works. However, I want to be able to read and send smaller pieces (~4k).
  • If I add a Thread.sleep(100) after sending each binary message I works.

Here is the code I'm using:

// A text message arrived from the server.
public void onTextMessage(WebSocket websocket, String message) {  
  if (message != "listening")
    return;

  try {
    byte[] buffer = new byte[4096]; // 4k
    int read;
    while ((read = inputStream.read(buffer)) > 0) {
      if (read == 4096)
        socket.sendBinary(buffer);
      else {
        byte[] last = Arrays.copyOfRange(buffer, 0, read);
        socket.sendBinary(last);
      }
    }
  } catch (IOException e) {
    delegate.onError(e);
  } 
}
  • Is there a way to enable debugging?
  • Which thread is it using to send the audio? could that be the problem?
@germanattanasio
Copy link
Author

Reading the documentation seems like the problem could be that the ReadingThread is calling sendBinary().

I think I'm completely lost. 😲

@TakahikoKawasaki
Copy link
Owner

if (message != "listening")

This is a beginners' bug. Use equals(Object) method when you compare strings.

@TakahikoKawasaki
Copy link
Owner

Don't write a while loop in a callback method such as onTextMessage. Program within a callback method should finish as quickly as possible. This rule is not specific to nv-websocket-client. Rather, it is a general rule (i.e. programming basics). If you want to trigger something that takes a long time, it should be done asynchronously.

@TakahikoKawasaki
Copy link
Owner

A WebSocket message (text message or binary message) consists of one or more frames. sendBinary() sends one binary frame and the frame composes one binary message.

If you want to send one binary message that consists of multiple frames, you have to do the following.

  1. sendBinary(...data..., false)
  2. sendContinuation(...data...)
  3. ....
  4. sendContinuation(...data..., true)

See "Send Frames" in README.md for details.

@germanattanasio
Copy link
Author

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants