Socket網絡編程(二)
阿新 • • 發佈:2018-11-29
length public ket client pack net pan .get clas
udp協議發送消息案例
1、創建UdpServer(udp服務器端)
package com.cppdy.udp; import java.net.DatagramPacket; import java.net.DatagramSocket; //udp服務器端 public class UdpServer { public static void main(String[] args) throws Exception { System.out.println("udp服務啟動……"); DatagramSocket ds = new DatagramSocket(8080);byte[] buf = new byte[1024]; DatagramPacket dp = new DatagramPacket(buf, buf.length); ds.receive(dp); String add = dp.getAddress().toString(); String data = new String(dp.getData(), 0, dp.getLength()); System.out.println("服務器接受:從IP" + add + "傳輸的數據:" + data); } }
2、創建UdpClient(udp客戶端)
package com.cppdy.udp; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; //udp客戶端 public class UdpClient { public static void main(String[] args) throws Exception { String msg = "吹泡泡的魚"; DatagramSocket ds= new DatagramSocket(); byte[] bytes = msg.getBytes(); DatagramPacket dp = new DatagramPacket(bytes, bytes.length, new InetSocketAddress("127.0.0.1", 8080)); ds.send(dp); ds.close(); System.out.println("客戶端發送信息完畢……"); } }
Socket網絡編程(二)