jdk6.0从入门到精通-----chapter5网络编程 udp套接字

用到的主要类DatagramPacket,DatagramSocket
DatagramSocket类用于创建接收和发送UDP的sockect实例。
构造器
DatagramSocket():通常用于客户端编程
DatagramSocket(int prot) :固定监听prot端口的报文
最主要的方法有:
receive(DatagramPacket p)接收报文到p中,
send(DatagramPacket p)发送报文
close()

DatagramPacket 处理报文,将字节数组,目标地址,目标端口等数据包装成报文或者将报文拆分成字节数组

接收端


package udp;

import java.net.InetAddress;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPReceive 
{
	public static void main(String args[]) 
  {
  	try 
    {
    	if (args.length != 1) 
        throw new IllegalArgumentException("Wrong number of args");
      int port = Integer.parseInt(args[0]);
      DatagramSocket dsocket = new DatagramSocket(port);
      byte[] buffer = new byte[2048];
      DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
      for(;;) 
      {
      	dsocket.receive(packet);
        String msg = new String(buffer, 0, packet.getLength());
        System.out.println(packet.getAddress().getHostName() + ": " + msg);
        packet.setLength(buffer.length);
      }
    }
    catch (Exception e) 
    {
    	System.err.println(e);
    }
  }
}


发送端
package udp;

import java.net.InetAddress;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPSend 
{
	public static void main(String args[]) 
  {
  	try 
    {
    	if (args.length < 3)     
        throw new IllegalArgumentException("Wrong number of args");
      String host = args[0]; //ip地址
      int port = Integer.parseInt(args[1]);//端口
      byte[] message;
      String msg = args[2];  //发送信息
      message = msg.getBytes();
      InetAddress address = InetAddress.getByName(host);
      DatagramPacket packet = new DatagramPacket(message, message.length,address, port); //
      DatagramSocket dsocket = new DatagramSocket();
      dsocket.send(packet);
      dsocket.close();
    }
    catch (Exception e) 
    {
    	System.err.println(e);
    }
  }
}

执行时,在cmd中先启动接收端

E:\Eclipse workspace\ch05\src>java udp.UDPReceive 8888

在打开一个cmd,启动发送端
E:\Eclipse workspace\ch05\src>java udp.UDPSend localhost 8888 hello
会在接收端显示:localhost: hello
缺点:
客户端只能发送一次就结束了

你可能感兴趣的:(java,eclipse,编程,.net)