总结:
接收端程序编写:
①调用DatagramSocket(int port)创建一个数据报套接字,并绑定到指定端口上;②调用DatagramPacket(byte[] buf, int length),建立一个字节数组以接收UDP包 。③调用DatagramSocket类的receive(),接收UDP包。④最后关闭数据报套接字。
发送端程序编写:
①调用DatagramSocket()创建一个数据报套接字; ②调用DatagramPacket(byte[] buf, int offset, int length, InetAddress address, int port),建立要发送的UDP包。 ③调用DatagramSocket类的send(),发送UDP包。④最后关闭数据报套接字。
实例:使用UDP模拟一个接收端和一个客户端,完成其中的通讯。
接收端(单线程):
package cn.com.xinli.test.socket; import java.net.DatagramPacket; import java.net.DatagramSocket; public class UDPSocketServer extends Thread { public static void recv() { try { System.out.println("接收端启动!"); DatagramSocket ds=new DatagramSocket(6000); byte[] buf=new byte[100]; DatagramPacket dp=new DatagramPacket(buf,100); ds.receive(dp); System.out.println(new String(buf,0,dp.getLength())); String str="Welcome you!"; DatagramPacket dpSend=new DatagramPacket(str.getBytes(),str.length(), dp.getAddress(),dp.getPort()); ds.send(dpSend); ds.close(); } catch (Exception ex) { ex.printStackTrace(); } } public static void main(String[] args) { UDPSocketServer socketServer=new UDPSocketServer(); socketServer.recv(); } }
11.12,光棍节过后的第一天,到处看看,发现我这个UDP的客户端是单线程的,于是改吧改吧,弄成个多线程的玩玩,听说现在找工作都爱考多线程并发编程啥的,哎我的软肋呀!!
接收端(多线程):
package cn.com.xinli.test.socket; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class UDPSocketServer extends Thread { private DatagramSocket ds; private DatagramPacket dp; UDPSocketServer(DatagramSocket ds,DatagramPacket dp) { this.ds=ds; this.dp=dp; } UDPSocketServer() { } @Override public void run() { try { String str="Welcome you!"; DatagramPacket dpSend=new DatagramPacket(str.getBytes(),str.length(), dp.getAddress(),dp.getPort()); ds.send(dpSend); // ds.close(); } catch (Exception ex) { ex.printStackTrace(); } } public void recv() { int port=3333; System.out.println("接收端启动,监听端口:"+port); try { byte[] buf=new byte[100]; ds=new DatagramSocket(port); while(true) { dp=new DatagramPacket(buf,100); ds.receive(dp); System.out.println("发送端说:"+new String(buf,0,dp.getLength())); new UDPSocketServer(ds,dp).start(); } } catch (Exception ex) { ex.printStackTrace(); } } public static void main(String[] args) throws SocketException { UDPSocketServer socketServer=new UDPSocketServer(); socketServer.recv(); } }
发送端:
package cn.com.xinli.test.socket; import java.net.*; import java.io.*; public class UDPSocketClient { public static void main(String[] args) { UDPSocketClient.send(); } public static void send() { try { System.out.println("发送端启动!"); DatagramSocket ds=new DatagramSocket(); String str="Hello,this is zhangsan"; DatagramPacket dp=new DatagramPacket(str.getBytes(),str.length(), InetAddress.getByName("localhost"), 6000); ds.send(dp); byte[] buf=new byte[100]; DatagramPacket dpRecv=new DatagramPacket(buf,100); ds.receive(dpRecv); System.out.println(new String(buf,0,dpRecv.getLength())); ds.close(); } catch (Exception ex) { ex.printStackTrace(); } } }
测试:接收和发送正常