客户端和服务器UDP传输层

时间:2014-03-03 07:07:45

标签: udp udpclient

我需要从客户端向服务器发送一条消息“Hi”,服务器将回复客户端添加收到的消息“已接收”,一旦客户端收到此新消息,它就会将此消息发送给另一台服务器并且该服务器将向收到的消息添加另一条消息,说“已回复”。因此,最终客户端将收到消息“Hi Received Replied”。 客户代码:

public class UDPClient{    

public static void main(String args[]) {  
        // args[0] = message to be sent to the server; 
    // args[1] = IP address of the server

    DatagramSocket aSocket=null;
    try {
        aSocket=new DatagramSocket();
        byte [] m = args[0].getBytes();
        InetAddress aHost = InetAddress.getByName(args[1]);
        int serverPort = 6789;

DatagramPacket request = new DatagramPacket(m,args[0].length(), aHost, serverPort);
        aSocket.send(request);                                  

        byte[] buffer = new byte[1000];
        DatagramPacket reply = new DatagramPacket(buffer,buffer.length);
        aSocket.receive(reply);     
System.out.println("Reply: " + new String(reply.getData(), 0, reply.getLength()));

    }catch (SocketException e){System.out.println("Socket: " + e.getMessage());
    }catch (IOException e){System.out.println("IO: " + e.getMessage());
    }finally {
        if(aSocket != null) aSocket.close();
    }
}
}

服务器代码:

public class UDPServer{    
public static void main(String args[]) {        
   DatagramSocket aSocket = null;

try{            
    aSocket = new DatagramSocket(6789);  
    byte[] buffer = new byte[1000];             
    while(true){                
DatagramPacket request = new DatagramPacket(buffer,buffer.length);
aSocket.receive(request); 

System.out.println("Server is ready and waiting for requests ... "); 
DatagramPacket reply = new DatagramPacket(request.getData(), request.getLength(),request.getAddress(), request.getPort());

     }      
}catch (SocketException e){System.out.println("Socket: " + e.getMessage());
}catch (IOException e) {System.out.println("IO: " + e.getMessage());
}finally {
    if(aSocket != null) aSocket.close();
}
  }
}

0 个答案:

没有答案