基本实现流程是:
1.调线程接收(这时候已经新建了DatagramSocket)
2.发指令(线程发送,保证发送时和接收用的是一个DatagramSocket)
首先,封装好收发方法
package com.nz.gatewaydemo.demo.gateway.util;
import java.io.IOException;
import java.net.*;
import java.util.Date;
/**
* @Author xxs
* @Date 2020/7/3 10:32
*/
public class SRData {
public DatagramSocket sockets;
public InetAddress address;
{
try {
sockets = new DatagramSocket(5000);
} catch (SocketException e) {
e.printStackTrace();
}
}
public SRData(){
new Thread() {
public void run() {
while (true){
receiveData(sockets);
}
}
}.start();
}
/**
* 发送数据
* @param data
*/
public void SendData(String data,String host,int port) {
/*
* 向服务器端发送
*/
//1.定义服务器地址,端口号,数据包
InetAddress address = null;
try {
address = InetAddress.getByName(host);
byte[] sendData = data.getBytes();
//2.创建数据包,包含发送的信息
DatagramPacket packet = new DatagramPacket(sendData, sendData.length, address, port);
//4.向服务器端发送数据包
new Thread() {
public void run() {
try {
sockets.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
System.out.println("---------xxs---------"+new Date() +"---------------------发送指令:"+data);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 接收数据
*/
public void receiveData(DatagramSocket sockets) {
/*
* 接收服务器端数据
*/
//1.创建数据包,用于接收回应数据
byte[] data2 = new byte[1024];
DatagramPacket packet2 = new DatagramPacket(data2, data2.length);
//2.接收数据
try {
sockets.receive(packet2);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//3.读取数据
String reply = new String(data2).trim();
address=packet2.getAddress();
System.out.println("---------xxs---------"+new Date() +"---------------------接收数据啦啦啦:"+address+":"+packet2.getPort());
System.out.println("---------xxs---------"+new Date() +"---------------------收到回应" + reply);
}
}
封装好你所发指令
main方法测试
我们启动main方法后