UDP方式的网络通信
客户端:
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; /** * UDP要进行数据的发送,需要首先拿到DatagramSocket * @author igeekhome * */ public class Sender { public static void main(String[] args) throws IOException { //设置发送数据报包的端口号 DatagramSocket socket = new DatagramSocket(8091); String data92 = "河神结束啦,大家快来学JAVA吧。。。92"; String data93 = "河神结束啦,大家快来学JAVA吧。。。93"; InetAddress address = InetAddress.getByName("localhost"); //创建数据报包对象,设置发送的数据,还有目的地的主机和端口号 192.168.13.2 192.168.13.5 DatagramPacket packet92 = new DatagramPacket(data92.getBytes(), data92.getBytes().length, address, 8092); DatagramPacket packet93 = new DatagramPacket(data93.getBytes(), data93.getBytes().length, address, 8093); //要发送数据需要调用socket的send方法 socket.send(packet92); socket.send(packet93); } }
收数据:
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class Reciver { public static void main(String[] args) throws IOException { //创建数据报包套接字 DatagramSocket socket = new DatagramSocket(8093); byte[] bs = new byte[1024]; DatagramPacket packet = new DatagramPacket(bs, bs.length); while(true){ //调用receive方法接收数据报包 socket.receive(packet); //获取数据报包中的数据 byte[] data = packet.getData(); System.out.println(new String(data)); } } }