Java UDP-从服务器向客户端发送字符串数组 [英] Java UDP - Sending a string array from server to client

查看:113
本文介绍了Java UDP-从服务器向客户端发送字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谢谢你,

因此,我试图获取一个JList项目数组并将其转换为字符串数组(我认为我已经正确),然后我尝试将该字符串数组发送给我的客户端,然后客户端将尝试将其显示回其旁边的JList中。

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

这是我最新的代码尝试将字符串数组发送过来:

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

该行: FilesBuffer = FilesList.getBytes(); 引起了这个问题,因为 getBytes()在这里不适用。

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

所以我的问题是:
1)如何将JList项目(它们是名称)的数组发送到客户端(它不一定是字符串数组),以及
2)我将如何接收

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?

谢谢。

推荐答案

必须为字符串数组制作二进制格式。

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();

此内部为String首先写入字节长度,并使用 String .getBytes( UTF-8)以便可以写入任何字符串。

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

这篇关于Java UDP-从服务器向客户端发送字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆