循环发送
package chat;import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetSocketAddress;/** * 发送方 */public class UdpSenderDemo1 { public static void main(String[] args) throws Exception { DatagramSocket socket = new DatagramSocket(8888); //准备数据:控制台读取:System.in BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (true){ String data = reader.readLine(); byte[] dataBytes = data.getBytes(); DatagramPacket packet = new DatagramPacket(dataBytes, 0 , dataBytes.length, new InetSocketAddress("localhost", 6666)); //发送数据包 socket.send(packet); //当发送一句 bye 的时候表示结束发送 if (data.equals("bye")){ break; } } //关闭 socket.close(); }}
接收消息
package chat;import java.net.DatagramPacket;import java.net.DatagramSocket;/** * 接收方 */public class UdpReceiveDemo1 { public static void main(String[] args) throws Exception { DatagramSocket socket = new DatagramSocket(6666); while (true){ //准备接收数据包 byte[] container = new byte[1024]; DatagramPacket packet = new DatagramPacket(container, 0, container.length); //接收数据包 socket.receive(packet); //阻塞式接收包裹 //读取数据 byte[] data = packet.getData(); String receiveData = new String(data, 0, data.length); //接收到的数据 System.out.println(receiveData); //当我们说一声 bye 的时候就表示断开连接 if (receiveData.equals("bye")){ break; } } //关闭 socket.close(); }}
原文转载:http://www.shaoqun.com/a/490662.html
hemingway:https://www.ikjzd.com/w/2344
jpgoodbuy:https://www.ikjzd.com/w/1553
转运中国:https://www.ikjzd.com/w/1549
网络编程之UDP实现聊天循环发送packagechat;importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.DatagramPacket;importjava.net.DatagramSocket;importjava.net.InetSocketAddress;/***发送方*/publiccla
sonar:sonar
vat:vat
珠江南田温泉有什么好玩的?:珠江南田温泉有什么好玩的?
普吉岛娱乐—普吉镇 :普吉岛娱乐—普吉镇
惠州叶挺纪念馆自驾游该如何安排呢?门票多少?:惠州叶挺纪念馆自驾游该如何安排呢?门票多少?
没有评论:
发表评论