首页 > 代码库 > JAVA基础知识之网络编程——-基于UDP协议的通信例子
JAVA基础知识之网络编程——-基于UDP协议的通信例子
UDP是一种不可靠的协议,它在通信两端各建立一个socket,这两个socket不会建立持久的通信连接,只会单方面向对方发送数据,不检查发送结果。
java中基于UDP协议的通信使用DatagramSocket类的receive和send方法即可,但消息需要通过一个特定的类封装(DatagramPacket)
下面是一个基于UDP协议的通信的例子,
服务器端,
1 package udp; 2 3 import java.io.IOException; 4 import java.net.DatagramPacket; 5 import java.net.DatagramSocket; 6 7 public class Server { 8 private static final int PORT = 3000; 9 //数据报大小 10 private static final int DATA_LEN = 4096; 11 //接受网络数据的字节数组 12 byte[] inBuff = new byte[DATA_LEN]; 13 //接收数据 14 private DatagramPacket inPacket = new DatagramPacket(inBuff, inBuff.length); 15 //发送数据 16 private DatagramPacket outPacket; 17 String[] books = new String[] 18 { 19 "疯狂英语", 20 "康熙词典", 21 "TCP协议", 22 "NIO非阻塞channel" 23 }; 24 public void init() throws IOException { 25 try { 26 DatagramSocket socket = new DatagramSocket(PORT); 27 for (int i = 0; i < 1000; i++) { 28 //读取socket中的数据 29 socket.receive(inPacket); 30 System.out.println(inBuff == inPacket.getData()); 31 System.out.println(new String(inBuff, 0, inPacket.getLength())); 32 33 byte[] sendData = http://www.mamicode.com/books[i % 4].getBytes(); 34 outPacket = new DatagramPacket(sendData, sendData.length, inPacket.getAddress(), PORT); 35 socket.send(outPacket); 36 } 37 } catch (IOException e) { 38 e.printStackTrace(); 39 } 40 } 41 42 public static void main(String[] args) throws IOException { 43 new Server().init(); 44 } 45 }
客户端,
1 package udp; 2 3 import java.io.IOException; 4 import java.net.DatagramPacket; 5 import java.net.DatagramSocket; 6 import java.net.InetAddress; 7 import java.util.Scanner; 8 9 public class Client { 10 private static final int PORT = 3000; 11 //数据报大小 12 private static final int DATA_LEN = 4096; 13 private static final String DEST_IP = "127.0.0.1"; 14 //接受网络数据的字节数组 15 byte[] inBuff = new byte[DATA_LEN]; 16 //接收数据 17 private DatagramPacket inPacket = new DatagramPacket(inBuff, inBuff.length); 18 //发送数据 19 private DatagramPacket outPacket; 20 21 public void init() throws IOException { 22 try { 23 //使用随机端口创建socket 24 DatagramSocket socket = new DatagramSocket(); 25 outPacket = new DatagramPacket(new byte[0], 0, InetAddress.getByName(DEST_IP), PORT); 26 Scanner scann = new Scanner(System.in); 27 while (scann.hasNextLine()) { 28 byte[] buff = scann.nextLine().getBytes(); 29 outPacket.setData(buff); 30 socket.send(outPacket); 31 socket.receive(inPacket); 32 System.out.println(new String(inBuff, 0, inPacket.getLength())); 33 } 34 } catch(IOException e) { 35 e.printStackTrace(); 36 } 37 } 38 39 public static void main(String[] args) throws IOException { 40 new Client().init(); 41 } 42 }
执行结果,启动一个服务器端,再启动一个客户端发一条信息,服务器端输出了信息,
JAVA基础知识之网络编程——-基于UDP协议的通信例子
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。