UDP
工具类
public classUDP {private static final int port = 9000; //要使用的端口号
/*** 发送消息
* @Param ip 对方的ip,String
* @Param msg 要发送的消息,String类型*/
public static void send(String ip,String msg) throwsIOException {//对方的ip,不能直接用String,需要转换一下
InetAddress ipAddr =InetAddress.getByName(ip);//socket,相当于码头
DatagramSocket socket = newDatagramSocket();//packet,数据包,相当于集装箱//参数:byte[]、数据长度、对方ip(不能直接写String)、要使用的端口号//什么类型都可以传输,比如传文件,不局限于String,因为都要转换为字节数组
DatagramPacket packet = newDatagramPacket(msg.getBytes(), msg.length(),ipAddr,port);//通过socket发送packet
socket.send(packet);
System.out.println("send:"+msg);//关闭socket
socket.close();
}/***监听端口,接收消息*/
public static void receive() throwsIOException {//socket,指定要监听的端口。发送、接收使用的