UDP簡單實現資訊的接收與傳遞(模擬聊天功能)
阿新 • • 發佈:2020-09-10
////簡單實現迴圈接收訊息
package com.cl.chat; ////簡單實現迴圈接收訊息 import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class UdpReceiveDemo01 { public static void main(String[] args) throws Exception { DatagramSocket socket = new DatagramSocket(6666);while (true) { //準備接收位元組 byte[] data = new byte[1024]; DatagramPacket packet = new DatagramPacket(data, 0, data.length); socket.receive(packet);//阻塞時接收 byte[] data1 = packet.getData(); String receiveData = new String(data1, 0, data1.length); System.out.println(receiveData); if (receiveData.equals("bye")) { //斷開連線 break; } } socket.close(); } }
////簡單實現迴圈接收訊息
package com.cl.chat; ////簡單實現迴圈接收訊息 import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException;public class UdpReceiveDemo01 { public static void main(String[] args) throws Exception { DatagramSocket socket = new DatagramSocket(6666); while (true) { //準備接收位元組 byte[] data = new byte[1024]; DatagramPacket packet = new DatagramPacket(data, 0, data.length); socket.receive(packet);//阻塞時接收 byte[] data1 = packet.getData(); String receiveData = new String(data1, 0, data1.length); System.out.println(receiveData); if (receiveData.equals("bye")) { //斷開連線 break; } } socket.close(); } }