客户端:
package cn.zyw.javaurl; import java.io.IOException; import java.net.*; /** * Created by zyw on 2016/4/2. */ public class UDPClient { public static void main(String args[]){ try { DatagramSocket clientsocket=new DatagramSocket(); String senddata="hello my name is zyw"; byte[] bytes=senddata.getBytes(); InetAddress ip=InetAddress.getByName("127.0.0.1"); DatagramPacket packet=new DatagramPacket(bytes,0,senddata.length(),ip,7777); clientsocket.send(packet); byte data[]=new byte[1024]; DatagramPacket packet1=new DatagramPacket(data,0,data.length); clientsocket.receive(packet1); String s=new String(data,0,packet1.getLength()); System.out.println("server say:"+s); } catch (SocketException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } } }
服务器:
package cn.zyw.javaurl; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; /** * Created by zyw on 2016/4/2. */ public class UDPServer { public static void main(String args[]){ try { DatagramSocket serversocket=new DatagramSocket(7777); byte[] data=new byte[1024]; DatagramPacket packet=new DatagramPacket(data,data.length); System.out.println("服务器已启动......"); serversocket.receive(packet); String s=new String(data,0,packet.getLength()); System.out.println("get client:"+s); DatagramSocket clientsocket=new DatagramSocket(); String senddata="welcome to you visit "; byte[] bytes=senddata.getBytes(); InetAddress ip=packet.getAddress(); int port=packet.getPort(); DatagramPacket p=new DatagramPacket(bytes,0,senddata.length(),ip,port); clientsocket.send(p); } catch (SocketException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } } }