UDP循环发送消息

Posted 逆骨111

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UDP循环发送消息相关的知识,希望对你有一定的参考价值。

package kuangs.chat;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.stream.Stream;

//发送方
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();
}
}




package kuangs.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[] container = new byte[1024];
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();
}
}

以上是关于UDP循环发送消息的主要内容,如果未能解决你的问题,请参考以下文章

发送UDP广播,接收多条消息

BitTorrent:发送请求的最佳速率?

C#基于UDP实现简单客户端和服务器消息发送和接收

C#-Lua UDP不兼容(未收到消息)

VB6 应用程序通过 winsock 发送 UDP 广播消息 - 仅每秒发送一次消息

接收 UDP 消息