www.pudn.com > exercise.rar > UDPSend.java


import java.net.*; 
import java.io.*; 
class UDPSend 
{ 
	public static void main(String[] args)  
	{ 
		int argc=args.length; 
 
		if (args.length!=1) 
        { 
             System. out. println("hostname: "); 
			 return; 
		} 
                     
	    String hostname=args[0]; 
 
		 
		 
		try{ 
           DatagramSocket socket = new DatagramSocket(2001); 
		   //socket 绑定到一个本地的可用端口,等待接收客户端的请求。 
		   System. out. println("Bound to local port: "+socket.getLocalPort()); 
 
           ByteArrayOutputStream bout= new ByteArrayOutputStream(); 
		   PrintStream pout=new PrintStream(bout); 
		   pout.print("I send it to you."); 
            
		   byte[] barry=bout.toByteArray(); 
 
           DatagramPacket packet = new DatagramPacket(barry, barry.length); 
 
           System. out. println("looking up hostname "+hostname); 
		   InetAddress remote_addr=InetAddress.getByName(hostname); 
 
		   packet.setAddress(remote_addr); 
		   packet.setPort(2000);  
		    
		   socket.send(packet); 
		   System. out. println("Packet is sent."); 
		   socket.close(); 
        }catch(java.net.UnknownHostException uhe) { 
			System. out. println("UnknownHostException");} 
		 
		catch(java.net.SocketException se) { 
			System. out. println("SocketException"+se);} 
		catch(IOException ioe) { 
		    System. out. println("IOException");} 
      
         
		 
	} 
}