Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 views
in Technique[技术] by (71.8m points)

Java UDP - Sending a string array from server to client

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

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

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...