Reputation: 1223
I wrote this program called echo Server.It has two files i.e., a sender
and receiver.
The sender sends data using Datagram sockets and Datagram packets and the server(receiver) echoes the same thing back.
But the message echoed back is not the same as that is sent.
The output is not proper.Why is this happening?
Sender Program
import java.net.*;
import java.io.*;
public class sender {
public static void main(String[] args){
try{
DatagramSocket ds = new DatagramSocket();
InetAddress ip = InetAddress.getByName("localhost");
int port = 1234;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String msg = br.readLine();
byte[] buf = new byte[100];
while(true){
DatagramPacket dp = new DatagramPacket(msg.getBytes(),msg.length(),ip,port);
if(!msg.equals("quit"))
ds.send(dp);
else { ds.send(dp);break;}
dp = new DatagramPacket(buf,buf.length);
ds.receive(dp);
msg = new String(buf);
System.out.println(msg);
msg = br.readLine();
}
//ds.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
Receiver(Server) Program
import java.net.*;
import java.io.*;
public class receiver {
public static void main(String[] args){
try{
DatagramSocket ds = new DatagramSocket(1234);
DatagramSocket sds = new DatagramSocket();
byte[] buf = new byte[100];
String msg;
DatagramPacket rdp,sdp;
while(true)
{
rdp = new DatagramPacket(buf,buf.length);
ds.receive(rdp);
msg = new String(buf);
msg = msg.trim();
if(!msg.equals("quit"))
System.out.println(msg);
else break;
sdp = new DatagramPacket(msg.getBytes(),msg.length(),rdp.getAddress(),rdp.getPort());
sds.send(sdp);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
Upvotes: 0
Views: 422
Reputation: 311054
msg = new String(buf);
The problem is here. You're ignoring the length in the datagram. It should be:
msg = new String(rdp.getData(), rdp.getOffset(), rdp.getLength());
Then:
msg = msg.trim();
You don't need that. Remove.
Upvotes: 1
Reputation: 129
byte[] buf = new byte[100];
Is created once, but afterwards never cleared. So when the next message is shorter than the previous a part of the old data remains and thus you get faulty data on both ends.
Try clearing the buffer at the start of your while loop.
while(true){
buf = new byte[100];
Upvotes: 0