views:

90

answers:

1

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?

+4  A: 

Your problem has nothing to do with the StringBuffer, but with this line:

sentence = new String(receivePacket.getData());

You're turning the whole buffer into a string, when the sender may have sent less than the size of the buffer. So you get a bunch of zero bytes in the resulting string, which cause the data you print to be truncated.

You need to truncate the receive buffer based on how much data was actually read:

sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
vanza
Thanks. I didn't think about the zero bytes. Now it works as I wish.
Bevor