Hello, my target is it to collect data from clients which send data to an UDP server, concatenate the data in a string (just for testing now) and send the whole concatenated string back to the client. The communication between UDPClient and UDPServer works perfect. I can send data and receive it. But I wonder why I can't concatenate the data in a StringBuffer, because when I try that, the client always gets the very first string I ever sent. And the string does not change anymore regardless of what I'm sending to the server. Here is the code of the server class:
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();
}
}
}
}
I already debugged it: The variable "sentences" always gets the right data, but the line data.append(sentence); doesn't do anything. It just doesn't append the data. Why is this so?