package Internet;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
// UDP实现聊天,两边都是发信方,也是收信方
public class Test10_UDP_Me {
public static void main(String[] args) throws Exception {
// 1. 创建自己的端口
DatagramSocket socket = new DatagramSocket(2005);
// 2. 不断地建立包裹并发送出去: 可以不停地发消息
// 从控制台键盘读取信息,并且发送出去
while (true){
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String msg= reader.readLine();
// byte[] data=(byte[])reader; 这里不能强制转换
DatagramPacket packet = new DatagramPacket(msg.getBytes(),0,msg.length(),new InetSocketAddress("localhost",2000));
socket.send(packet);
if (msg.equals("bye")){
break;
} // 结束判定
}
// 3. 关闭
socket.close();
}
}
///////////////////
package Internet;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class Test10_UDP_MyBrother {
public static void main(String[] args) throws Exception {
// 1. 创建自己的端口
DatagramSocket socket = new DatagramSocket(2000);
// 2. 不停地接收包裹:可以不停地接收信息
while (true){
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
socket.receive(packet); // 阻塞式接收:有就接收
String msg=new String(packet.getData(),0,packet.getLength());
System.out.println(msg);
if (msg.equals("bye")){
break;
}
}
// 3. 关闭
socket.close(); // 阻塞式接收:不断地接收
}
}
标签:DatagramSocket,10,UDP,java,packet,聊天,import,msg,new
From: https://www.cnblogs.com/zhanjianhai/p/17690004.html