java socket UDP协议收发数据简单实现通信示例

2/10/2017来源:ASP.NET技巧人气:1116

server端: package gxltest; /** * Created by Administrator on 2016/12/2. */ import java.net.DatagramPacket; import java.net.DatagramSocket; public class UDPServer { public static void main(String[] args) throws Exception{ DatagramSocket datagramSocket=new DatagramSocket(8088); while(true){ DatagramPacket packet=new DatagramPacket(new byte[512], 512); datagramSocket.receive(packet); String msg=new String(packet.getData(), 0, packet.getLength()); System.out.PRintln(packet.getAddress()+"/"+packet.getPort()+":"+msg); packet.setData("I am server!!!".getBytes()); datagramSocket.send(packet); } } }client端: package gxltest; /** * Created by Administrator on 2016/12/2. */ import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class UDPClient { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket datagramSocket=new DatagramSocket(); InetAddress address=InetAddress.getByName("GXL"); String msg="654"; while((msg=reader.readLine())!=""){ //发送数据 byte[] buffer=msg.getBytes(); DatagramPacket packet=new DatagramPacket(buffer, buffer.length, address, 8088); datagramSocket.send(packet); //接收数据 DatagramPacket inputPacket = new DatagramPacket(new byte[512], 512); datagramSocket.receive(inputPacket); System.out.println(new String(inputPacket.getData(), 0 , inputPacket.getLength())); datagramSocket.close(); } } }