Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Hi and thanks in advance,

So I'm trying to take an array of JList items and convert them to a string array (which I think I've gotten right), and then I'm trying to send that string array over to my client who will then attempt to display them back into a JList on their side.

I've tried a few different things but none are working.

Here is my latest code attempt to send the string array over:

String[] FilesList = (String[]) lClient1Files.getSelectedValues();

FilesBuffer = FilesList.getBytes();

DatagramPacket DGPFilesResponse = new DatagramPacket(FilesBuffer,FilesBuffer.length, DGP.getAddress(), DGP.getPort());
SeederSocket.send(DGPFilesResponse);

The line: FilesBuffer = FilesList.getBytes(); is causing the issue because getBytes() isn't applicable here.

So my questions are: 1) How do I send the array of JList items(they are names) over to the client (it doesn't particularly have to be a string array), and 2) How would I receive the list on the clients side, so that I can use it?

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
490 views
Welcome To Ask or Share your Answers For Others

1 Answer

One must make a binary format for the string array.

ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (DataOutputStream dos = new DataOutputStream(baos)) {
    dos.writeInt(filesList.length);
    for (String files : filesList) {
        dos.writeUTF(files);
    }
}
byte[] bytes = baos.toByteArray();

This internally for a String writes first the length in bytes, and uses String.getBytes("UTF-8") so any string can be written.

Reading goes with the reversed input classes.

If you think of having many clients out there, maybe with different versions, then add in the message a version number.


On the other side

ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
try (DataInputStream dis = new DataInputStream(baos)) {
    int stringsCount = dis.readInt();
    String[] filesList = new String[stringsCount];
    for (int i = 0; i < stringsCount; ++i) {
        filesList[i] = dis.readUTF();
    }
    return filesList;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...