最近项目中需要用到通信这块,与上位机交互,考虑udp相对于tcp传输速度快,并且不需要三次握手,这里用了MulticastSocket来实现udp通信.
实现思路:
DatagramPacket中
第一个参数:存放数据的字节数组;第二个参数:存放数据的字节长度;第三个参数:指定链接的ip地址(IP地址的范围是224.0.0.0至239.255.255.255);第四个参数:端口号
(1)建立链接
multicastSocket.joinGroup(address);
(2)发送方法
multicastSocket.send(datagramPacket);
(3)接受方法
multicastSocket.receive(datagramPacket); // 接收数据,同样会进入阻塞状态
这里贴上客户端code:
import java.io.IOException;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MulticastSocket extends Thread {
static java.net.MulticastSocket multicastSocket;
public static void main(String[] args) {
try {
multicastSocket = new java.net.MulticastSocket(58432);
InetAddress address = InetAddress.getByName("234.5.6.7");
multicastSocket.joinGroup(address);
byte[] buf = new byte[1024];
while (true) {
DatagramPacket datagramPacket = new DatagramPacket(buf,
buf.length);
multicastSocket.receive(datagramPacket); // 接收数据,同样会进入阻塞状态
byte[] message = new byte[datagramPacket.getLength()]; // 从buffer中截取收到的数据
System.arraycopy(buf, 0, message, 0, datagramPacket.getLength());
System.out.println(datagramPacket.getAddress());
System.out.println(new String(message));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // 接收数据时需要指定监听的端口号
}
public void run() {
// TODO Auto-generated method stub
while (true) {
byte[] buf = new byte[1024];
DatagramPacket datagramPacket;
try {
datagramPacket = new DatagramPacket(buf, buf.length,
InetAddress.getByName("234.5.6.7"), 58432);
multicastSocket.send(datagramPacket);
// multicastSocket.close();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}