Java Socket UDP编程
1 package com; 2 3 import java.io.IOException; 4 import java.net.*; 5 6 /** 7 * UDP Client 8 * 9 * Created by Administrator on 2018/5/3. 10 */ 11 public class Client { 12 13 public static void main(String[] args) throws IOException { 14 15 /** 16 * send message 17 */ 18 InetAddress inetAddress = InetAddress.getByName("localhost"); 19 byte[] data = "name:tom, pwd:123".getBytes(); 20 DatagramPacket datagramPacket = new DatagramPacket(data, data.length, inetAddress, 8800); 21 DatagramSocket datagramSocket = new DatagramSocket(); 22 datagramSocket.send(datagramPacket); 23 24 /** 25 * receive message 26 */ 27 byte[] data2 = new byte[1024]; 28 DatagramPacket datagramPacket1 = new DatagramPacket(data2, data2.length); 29 datagramSocket.receive(datagramPacket1); 30 String info = new String(data2, 0, data2.length); 31 System.out.println("I am Client, Server say:" + info); 32 33 /** 34 * close resource 35 */ 36 datagramSocket.close(); 37 } 38 }
1 package com; 2 3 import java.io.IOException; 4 import java.net.DatagramPacket; 5 import java.net.DatagramSocket; 6 import java.net.InetAddress; 7 8 /** 9 * UDP Server 10 * 11 * Created by Administrator on 2018/5/3. 12 */ 13 public class Server { 14 15 public static void main(String[] args) throws IOException { 16 17 DatagramSocket datagramSocket = new DatagramSocket(8800); 18 19 /** 20 * receive message 21 */ 22 byte[] bytes = new byte[1024]; 23 DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length); 24 datagramSocket.receive(datagramPacket); 25 String info = new String(bytes, 0, datagramPacket.getLength()); 26 System.out.println("I am Server, Client say: " + info); 27 28 /** 29 * send message 30 */ 31 InetAddress inetAddress = datagramPacket.getAddress(); 32 int port = datagramPacket.getPort(); 33 byte[] data = "welcome!".getBytes(); 34 DatagramPacket datagramPacket1 = new DatagramPacket(data, data.length, inetAddress, port); 35 datagramSocket.send(datagramPacket1); 36 37 /** 38 * close resource 39 */ 40 datagramSocket.close(); 41 } 42 }