我的目标是从客户端收集数据,该客户端将数据发送到UDP服务器,将数据串联为一个字符串(仅用于测试),然后将整个串联的字符串发送回客户端。UDPClient和UDPServer之间的通信非常完美。我可以发送和接收数据。但是我不知道为什么不能在StringBuffer中连接数据,因为当我尝试这样做时,客户端总是得到我发送过的第一个字符串。而且,无论我要发送到服务器什么,字符串都不会更改。这是服务器类的代码:
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; public class UDPServer extends Thread { DatagramSocket serverSocket; DatagramPacket receivePacket; String sentence; InetAddress IPAddress; StringBuffer data = new StringBuffer(); public UDPServer() throws SocketException { serverSocket = new DatagramSocket(9876); } public void run() { while (true) { byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; receivePacket = new DatagramPacket(receiveData, receiveData.length); try { serverSocket.receive(receivePacket); } catch (IOException e) { System.out.println("receive...."); e.printStackTrace(); } sentence = new String(receivePacket.getData()); IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); data.append(sentence); sendData = data.toString().trim().getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); try { serverSocket.send(sendPacket); } catch (IOException e) { System.out.println("send..."); e.printStackTrace(); } } } }
我已经调试了它:变量“句子”总是获得正确的数据,但是行data.append(sentence); 什么也没做 它只是不附加数据。为什么会这样呢?
您的问题与StringBuffer无关,而是与以下行有关:
sentence = new String(receivePacket.getData());
当发送方发送的缓冲区小于缓冲区的大小时,您会将整个缓冲区转换为字符串。因此,在结果字符串中会得到一堆零字节,这会导致您打印的数据被截断。
您需要根据实际读取的数据量截断接收缓冲区:
sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());