Java编写UDP两个主机之间互相发送和接收数据包
时间: 2023-07-30 08:05:22 浏览: 101
好的,我可以为你提供一个简单的Java程序,实现UDP两个主机之间互相发送和接收数据包。
首先,你需要了解一下UDP协议和Java中的DatagramSocket和DatagramPacket类。UDP协议是一种无连接的协议,不保证可靠传输,但是传输速度快,适用于对实时性要求较高的场景。DatagramSocket和DatagramPacket是Java中用于实现UDP通信的类。
下面是一个简单的Java程序,实现两个主机之间互相发送和接收数据包:
```java
import java.net.*;
public class UDPSenderReceiver {
public static void main(String[] args) throws Exception {
int port = 12345;
InetAddress receiverAddress = InetAddress.getByName("接收方主机IP地址");
DatagramSocket senderSocket = new DatagramSocket();
DatagramSocket receiverSocket = new DatagramSocket(port);
Sender sender = new Sender(senderSocket, receiverAddress, port);
Receiver receiver = new Receiver(receiverSocket);
sender.start();
receiver.start();
}
}
class Sender extends Thread {
private DatagramSocket senderSocket;
private InetAddress receiverAddress;
private int port;
public Sender(DatagramSocket senderSocket, InetAddress receiverAddress, int port) {
this.senderSocket = senderSocket;
this.receiverAddress = receiverAddress;
this.port = port;
}
public void run() {
try {
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
while (true) {
byte[] sendData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, receiverAddress, port);
senderSocket.send(sendPacket);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Receiver extends Thread {
private DatagramSocket receiverSocket;
public Receiver(DatagramSocket receiverSocket) {
this.receiverSocket = receiverSocket;
}
public void run() {
try {
while (true) {
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
receiverSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在程序中,我们创建了两个线程Sender和Receiver,分别用于发送和接收数据包。Sender从控制台读取用户输入的信息,并将信息发送给接收方主机;Receiver监听本地端口,接收来自发送方主机的数据包,并将数据包中的信息打印在控制台上。
你需要根据实际情况填写接收方主机的IP地址和端口号。在运行程序时,你可以在控制台上输入信息并发送给接收方主机,同时也可以接收来自接收方主机的信息。
以上就是一个简单的Java程序,实现UDP两个主机之间互相发送和接收数据包。希望能对你有所帮助!
阅读全文