简介:
在当前的网络通信中有三种通信模式:单播、广播和多播(组播),其中多播出现时间最晚,同时具备单播和广播的优点。
单播:单台主机与单台主机之间的通信
广播:当台主机与网络中的所有主机通信
多播:当台主机与选定的一组主机的通信
- 单播:单播地址是IP网络中最常见的。包含单播目标地址的分组发送给特定主机,一个这样的例子是,IP地址为192.168.1.5(源地址)的主机向IP地址为192.168.1.200(目标地址)的服务器请求网页,这是最常见的请求方式,java实例代码如下,我们采用的是UDP通讯方式DatagramSocket,和TCP的ServerSocket的区别在于
ServerSocket需要客户端先连接上服务段才能发送数据,而DatagramSocket不需要,但显然UDP是不是一定送达的
package net;
import java.io.IOException;
import java.net.*;
import java.util.Arrays;
public class DanboDemo {
private static final int MAXREV = 255;
public static void sendMsg(String message) throws IOException {
byte[] msg = message.getBytes();
DatagramSocket client = new DatagramSocket();
InetAddress inetAddr = InetAddress.getLocalHost();
SocketAddress socketAddr = new InetSocketAddress(inetAddr, 8888);
DatagramPacket sendPacket = new DatagramPacket(msg, msg.length,
socketAddr);
client.send(sendPacket);
client.close();
}
public static void received() throws IOException {
DatagramSocket server = new DatagramSocket(8888);
DatagramPacket recvPacket = new DatagramPacket(new byte[MAXREV], MAXREV);
while (true)
{
server.receive(recvPacket);
byte[] receiveMsg = Arrays.copyOfRange(recvPacket.getData(),
recvPacket.getOffset(),
recvPacket.getOffset() + recvPacket.getLength());
System.out.println("收到消息:" + new String(receiveMsg));
server.send(recvPacket);
}
}
public static void main(String[] args) throws IOException {
new Thread(()->{
try {
received();
} catch (IOException e) {
e.printStackTrace();
}
}
).start();
sendMsg("nihao");
sendMsg("kai lai le");
}
}