1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| package ADV_0; import java.io.DataOutputStream; import java.io.OutputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.Socket; import java.util.Scanner; public class ADVZc4K { public static void main(String[] args) throws Exception { System.out.println("======客户端开启======"); System.out.println("======UDP通信一发一收======"); DatagramSocket socket0 = new DatagramSocket(); byte[] bytes = "客户端".getBytes(); DatagramPacket packet0 = new DatagramPacket(bytes, bytes.length, InetAddress.getLocalHost(), 8080); socket0.send(packet0); socket0.close(); System.out.println("======UDP通信多发多收======"); DatagramSocket socket1 = new DatagramSocket(); Scanner sc0 = new Scanner(System.in); while (true) { System.out.println("请说:"); String msg = sc0.nextLine(); if ("exit".equals(msg)) { System.out.println("======退出======"); socket1.close(); break; } byte[] bytes1 = msg.getBytes(); DatagramPacket packet1 = new DatagramPacket(bytes1, bytes1.length, InetAddress.getLocalHost(), 8080); socket1.send(packet1); } System.out.println("===实现TCP通信下一发一收==="); Socket socket2 = new Socket("127.0.0.1", 9999); OutputStream os0 = socket2.getOutputStream(); DataOutputStream dos0 = new DataOutputStream(os0); dos0.writeInt(1); dos0.writeUTF("在吗?(小丑)"); socket2.close(); System.out.println("===实现TCP通信下多发多收==="); Socket socket3 = new Socket("127.0.0.1", 9999); OutputStream os1 = socket3.getOutputStream(); DataOutputStream dos1 = new DataOutputStream(os1); Scanner sc1 = new Scanner(System.in); while (true) { System.out.println("请说:"); String msg = sc1.nextLine(); if ("exit".equals(msg)) { System.out.println("退出成功!"); dos1.close(); socket3.close(); break; } dos1.writeUTF(msg); dos1.flush(); } } }
|