package edu.wtbu;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
public class Demo08 {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket();
while (true){
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String data = reader.readLine();
byte[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress("localhost",6666));
socket.send(packet);
if(data.equals("bye")){
break;
}
}
socket.close();
}
}
package edu.wtbu;标签:DatagramSocket,UDP,java,实现,聊天,new,import,net,data From: https://www.cnblogs.com/123456dh/p/17248609.html
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class Demo09 {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(6666);
while (true) {
//准备接收包裹
byte[] bytes = new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
socket.receive(packet);//阻塞式接收包裹
byte[] data = packet.getData();
String datas = new String(data, 0, data.length);
System.out.println(datas);
if(data.equals("bye")){
break;
}
}
socket.close();
}
}