Search code examples
javasocketsnio

How to send and receive multiple streams properly


I am trying to make something similiar to teamviewer, my server sends a command to the client, the client starts sending screenshots, i keep showing these in a JLabel, now if my server sends an other command say "stream audio", how can i make my client stream audio too along with the desktop stream (the server should be able to understand the which data is received)? should i use NIO? , I do not understand how NIO's could help in writing multiple outputs and reading mulitiple outputs.

Edit - For example my server sends a command and the client streams the screen in a new thread and my server again sends a command to get audio and my client starts an other thread to get audio, at this point there are two bytes coming in to the server, how can my server process them correctly?


Solution

  • You need to send a stream identifier and length before each stream. NIO will mostly get in the way. DataInput/OutputStreams are the way to go.

    A short or an int would do for the type, and an int (probably) for the length.

    dos.writeShort(type);
    dos.writeInt(length);
    dos.write(data);
    

    and ...

    int type = dis.readShort();
    int length = dis.readInt();
    byte[] buffer = new byte[length];
    dis.readFully(buffer);
    

    You should send a command when you have a command to send, but to read everything the client is sending you need another thread that is permanently in a read() loop until disconnection.

    is it right to disconnect the client if an IOException is thrown while reading or writing? or could it be because of some other reasons like delays?

    You should close the socket on any IOException other than `SocketTimeoutException.