UDP协议:
UDP协议传输数据是不可靠的,在java中,java.util.DatagramSocket负责接收和发送UDP数据报,java.util.DatagramPacket表示UDP数据表。每个
DatagramSocket与一个本底地址绑定,每个DatagramSocket可以把UDP数据报发送给任意一个远程DatagramSocket,也可以接收来自任意一个远程的
DatagramSocket的UDP数据报。在UDP数据报中包含了目的地址信息,DatagramSocket根据该信息把数据报发送到目的地
UDP服务端
public class EchoServer{ private int port = 8089; private DatagramSocket socket; public EchoServer()throws IOException{ socket = new DatagramSocket(port); System.out.println("服务端启动"); } public String ehco(String msg){ return "ehco:"+msg; } public void service(){ while(true){ try { //创建一个数据报对象 DatagramPacket packet = new DatagramPacket(new byte[512], 512); socket.receive(packet);//接收来自任意一个EhcoClient的数据报 String msg = new String(packet.getData(), 0, packet.getLength()); System.out.println(packet.getAddress()+":"+packet.getPort()+">"+msg); packet.setData(ehco(msg).getBytes());//给EchoClient发送数据报 socket.send(packet); } catch (Exception e) { e.printStackTrace(); } } } public static void main(String[] args) throws IOException { new EchoServer().service(); } }
UDP客户端
public class EchoClient { private String remoteHost = "localhost"; private int remotePort = 8089; private DatagramSocket socket; public EchoClient() throws SocketException{ socket = new DatagramSocket();//与本地任意的端口绑定 } public void talk() throws IOException{ try{ //获取服务端ip地址 InetAddress remoteIP = InetAddress.getByName(remoteHost); BufferedReader localReader = new BufferedReader(new InputStreamReader(System.in)); String msg = null; while((msg = localReader.readLine()) != null){ byte[] outputData = msg.getBytes(); DatagramPacket outputPacket = new DatagramPacket( outputData, outputData.length,remoteIP,remotePort); socket.send(outputPacket);//发送数据报 DatagramPacket inputPacket = new DatagramPacket(new byte[512], 512); socket.receive(inputPacket);//接收EchoServer的数据报 System.out.println(new String(inputPacket.getData(),0,inputPacket.getLength())); if(msg.equals("bye")){ break; } } }catch (Exception e) { e.printStackTrace(); }finally{ socket.close(); } } public static void main(String[] args) throws SocketException, IOException { new EchoClient().talk(); } }
来源:https://www.cnblogs.com/lazyli/p/10800470.html