JAVA 网络通信(一)
1. UDPSocket 套接字的使用
发送者不绑定端口的时候,默认是随机端口。发送消息你要指定你要发送的人!
创建发送者类
- 创建
DatagramSocket
实例对象 - 调用
DatagramSocket.send()
发送消息
2.1 将字符串对象(消息)转换为 byte 数组对象
2.2 获取 byte 数组对象 长度
2.3 获取接收者的 InetAddress 对象
2.4 获取接收者的端口 PORT - 调用
DatagramSocket.close()
释放资源
package com.raoLong.heima.learnSocket.UDP;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
* Author: RaoQingLong
* Date: 2021/2/6 22:05
* Description: 发送端
*/
public class Sender {
DatagramSocket senderSocket;
public Sender() throws Exception {
this.senderSocket = new DatagramSocket();
}
// 发送消息
public void sendMessage(String msg, String receiverIP, int receiverPort) throws Exception {
byte[] bytesData = msg.getBytes();
int dataLength = bytesData.length;
InetAddress receiverAddress = InetAddress.getByName(receiverIP);
System.out.println("开始发送消息");
this.senderSocket.send(
new DatagramPacket(
bytesData,
dataLength,
receiverAddress,
receiverPort
)
);
System.out.println("消息发送结束");
}
// 释放资源
public void close() {
this.senderSocket.close();
}
}
创建接收者类
- 创建
DatagramSocket
实例对象 - 创建
DatagramPacket
实例对象
2.1 创建 byte 数组容器用于接受消息
2.2 获取容器长度 - 调用
DatagramSocket.receive()
接受消息 - 接收到消息后解除阻塞状态,通过
DatagramPacket
实例对象获取数据
4.1 调用DatagramPacket.getAddress()
获取发送者的主机信息
4.2 调用DatagramPacket.getData()
获取消息的 byte 信息
package com.raoLong.heima.learnSocket.UDP;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
* Author: RaoQingLong
* Date: 2021/2/6 22:15
* Description: 接受者
*/
public class Receiver {
DatagramSocket receiverSocket;
final int PORT = 9090;
public Receiver() throws Exception {
this.receiverSocket = new DatagramSocket(this.PORT);
}
// 接受消息
public void receiveMessage() throws Exception {
byte[] messageContainer = new byte[1024];
DatagramPacket messagePackage = new DatagramPacket(messageContainer, messageContainer.length);
this.receiverSocket.receive(messagePackage);
// 获取消息发送者的主机对象
InetAddress senderAddress = messagePackage.getAddress();
// 获取数据
byte[] byteMessage = messagePackage.getData();
// 数组对象转换为字符串对象
String message = new String(byteMessage);
//输出打印消息
System.out.println(message);
}
}
调用接收者
package com.raoLong.heima.learnSocket.UDP;
/**
* Author: RaoQingLong
* Date: 2021/2/6 22:29
* Description: 接受者
*/
public class Receive {
public static void main(String[] args) throws Exception {
Receiver receiver = new Receiver();
receiver.receiveMessage();
}
}
调用发送者
package com.raoLong.heima.learnSocket.UDP;
/**
* Author: RaoQingLong
* Date: 2021/2/6 22:28
* Description: 接受执行类
*/
public class Send {
public static void main(String[] args) throws Exception {
Sender sender = new Sender();
sender.sendMessage(
"hello receiver!",
"192.168.56.1",
9090
);
}
}