Hi there,
I wrote this client/server code but i can't make it work.
and every time i try to debug the code the program goes in an infinite loop when executing the receive function.
This is the client code
package client;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class Client {
private DatagramSocket socket;
private DatagramPacket sendPacket;
public Client(){
try{
socket = new DatagramSocket();
}
catch ( SocketException socketException ){
socketException.printStackTrace();
System.exit( 1 );
}
}
public void run(){
while (true){
try{
String s="sana";
byte [] Sdata=s.getBytes();
sendPacket = new DatagramPacket( Sdata,
Sdata.length, InetAddress.getLocalHost(), 5000 );
socket.send(sendPacket);
ReceivePackets();
}
catch(Exception e){
e.printStackTrace();
}
}
}
public void ReceivePackets(){
try{
byte Rdata[] = new byte[ 100 ];
DatagramPacket receivePacket = new DatagramPacket(
Rdata, Rdata.length );
socket.receive( receivePacket );
System.out.println(receivePacket.getData());
}
catch(IOException e ){
e.printStackTrace();
}
}
}
This is the server code
package server;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class Server {
private DatagramSocket socket;
public Server(){
try{
socket =new DatagramSocket (5000);
}
catch(SocketException e){
e.printStackTrace();
}
}
public void run(){
while(true){
try{
byte [] Rdata=new byte[500];
DatagramPacket receivePacket =new DatagramPacket( Rdata, Rdata.length );
socket.receive( receivePacket );
System.out.println(receivePacket.getAddress());
sendPacket( receivePacket );
}
catch(IOException e ){
e.printStackTrace();
}
}
}
private void sendPacket(DatagramPacket receivePacket)
{
try{
DatagramPacket sendPacket = new DatagramPacket(
receivePacket.getData(), receivePacket.getLength(),
receivePacket.getAddress(), receivePacket.getPort());
socket.send( sendPacket );
}
catch(IOException e){
e.printStackTrace();
}
}
}
how to make it work?