UDP聊天实现:
本次尽实现发送方对接收方发送消息的功能,且能够不停的发送并接收消息,当消息为“bye”时,结束本次发送接收功能。
发送方:
public class UdpSenderDemo01 {
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[] 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();
}
}
接收方:
public class UdpReceiveDemo01 {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(6666);
//准备接收包裹
byte[] container = new byte[1024];
while (true){
DatagramPacket packet = new DatagramPacket(container,0,container.length);
socket.receive(packet);//阻塞式接收包裹
//断开连接 bye
byte[] data = packet.getData();
String receiveData = new String(data, 0, data.length);
System.out.println(receiveData);
if(receiveData.equals("bye")){
break;
}
}
socket.close();
}
}
需要注意的是在发送方中,有这么一段代码:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
这段代码的作用是,将在控制台输入的信息读取后存入reader中,也就是把我们想发送的消息读取出来,那么在配合下面的代码后,可以先将读取到的数据转换为String类型,再将其转换为字符型并且存入字节数组datas中,然后就可以通过DatagramPacket把消息发送给接收方啦。
我们在发送方的控制台输入想发送的消息:
然后我们来看看接收方的控制台:
我想,我们实现了消息发送的功能。