Reputation: 8959
Im trying to send a packet back to the user informing them of all the people currently on the server, when they send a message to the server which has the word "who" in it.
Here is my code:
else if( response.contains( "who" ) )
{
System.out.println( "Size of names collection: "+names.size() );
buf = null;
buf = names.toString().getBytes();
int thisPort = packet.getPort();
packet = new DatagramPacket( buf, buf.length,packet.getAddress(),thisPort );
socket.send(packet);
}
The output of the print statement above is 2 indicating that there are two people on, for example andrew and james. Now when I package it up and send it I would expect it to output this:
[Andrew, James]
But instead the client gets:
[Andrew,
And thats it. Whats the problem? BTW I have to use UDP for this and can't switch to TCP
UPDATE
Here is the code in the client class that receives the packets:
while( true )
{
try
{
// Set the buf to 256 to receive data back from same address and port
buf = null;
buf = new byte[256];
packet = new DatagramPacket(buf, buf.length, address, 4445);
socket.receive(packet);
String response = new String( packet.getData() );
// Receive the packet back
System.out.println( response );
}
catch( IOException e )
{
}
}
Upvotes: 0
Views: 2446
Reputation: 311039
Your datagram is being truncated to 256 byes because that's the size of the buffer you declared for the receiving DatagramPacket. If your datagrams can be longer, make the buffer bigger.
Best practice is to make it one bigger than the largest datagram you are expecting to receive. Then if you receive one that size you have an application protocol error.
Upvotes: 4
Reputation: 6130
You should check on both client and server the length of the DatagramPacket after the send/receive operation respectively (with the getLength method) to make sure it's the same, that would be the first hint. What Collection are you using for names?
Upvotes: 1
Reputation: 68536
Your question is incomplete. However..
UDP loses packets. That's why it's not reliable to use UDP for File Transfer purposes. The Adobe RTMFP uses UDP to transfer audio and video data in which many packets are lost., But audio/video content streaming is really faster when compared to TCP. I don't know if this answers your question, I just want to say that UDP does lose packets.
Upvotes: 0