关于org.tio.core.udp的UDP交互使用示例

java 复制代码
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.Node;
import org.tio.core.udp.UdpPacket;
import org.tio.core.udp.UdpServer;
import org.tio.core.udp.UdpServerConf;
import org.tio.core.udp.intf.UdpHandler;

import com.yanmade.configuration.Configuration;


public class NewMachineUdpHandler {

	private static Logger logger = LoggerFactory.getLogger(NewMachineUdpHandler.class);
	
	private static final String FORMAT = "$%s;%s\r\n";//$%s;%s\\r\\n	\r\n
	
	private static int LOCALPORT = 8090;
	private int newMachinePort = 9090;
	private static String newMachineHost = "172.16.55.100";
	private static final int TIMEOUT = 5000;
	
	private Node remoteNode = null;
	
	private UdpServer server = null;
	
	private int frameSequenceNum = 0;
	
	public static void main(String[] args) {
		newMachineHost = "192.168.230.205";
		
		newMachineHost = "127.0.0.1";
		
		
		Configuration.loadConfiguration();
		NewMachineUdpHandler h = new NewMachineUdpHandler();
		h.startTestCommand();
	}
	
	
	public NewMachineUdpHandler(int lPort,String rIp,int rPort) {
		LOCALPORT = lPort;
		newMachinePort = rPort;
		newMachineHost = rIp;
	}
	
	public NewMachineUdpHandler() {
		newMachinePort = Configuration.getConfigurationBean().newMachinePort;
		newMachineHost = Configuration.getConfigurationBean().newMachineHost;
		remoteNode = new Node(newMachineHost , newMachinePort);
		UdpServerConf udpServerConf = new UdpServerConf(LOCALPORT, new MyUdpHandler(), TIMEOUT);
		try {
			logger.info("LocalIp:{},LOCALPORT:{},newMachineHost:{},newMachinePort:{},",InetAddress.getLocalHost().getHostAddress(),LOCALPORT,newMachineHost,newMachinePort);
			server = new UdpServer(udpServerConf);
			server.start();
			logger.info("Success to init NewMachineUdpHandler.");
		} catch (SocketException e) {
			logger.error("Fail to init NewMachineUdpHandler.", e);
		} catch (UnknownHostException e) {
			logger.error("InetAddress.getLocalHost().getHostAddress().", e);
			e.printStackTrace();
		}
	}
	
	public boolean startTestCommand() {
		reset();
		sendData(String.format(FORMAT, frameSequenceNum++%255 , "start" ));
		for (int i = 0; i < 3; i++) {
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				logger.error("等待接受测试仪器的启动测试回送信息时被意外打断。errMsg:{}",e);
				Thread.currentThread().interrupt();
			}
			if(!isReceiveStart) {
				sendData(String.format(FORMAT, frameSequenceNum%255 , "start" ));
			}else {
				break;
			}
		}
		return isReceiveStart;
	}

	public void aboortTestCommand() {
		sendData(String.format(FORMAT, frameSequenceNum%255 , "abort" ));
		for (int i = 0; i < 3; i++) {
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				logger.error("等待接受测试仪器的终止测试回送信息时被意外打断。。errMsg:{}",e);
				Thread.currentThread().interrupt();
			}
			if(!isReceiveAbort) {
				sendData(String.format(FORMAT, frameSequenceNum%255 , "abort" ));
			}
		}
	}
	
	private void sendData(String str) {
		logger.info("sendData:{},newMachineHost:{},newMachinePort:{}",str,remoteNode.getIp(),remoteNode.getPort());
		server.send(str, remoteNode);
	}
	
	public void stop() {
		server.stop();
	}

	private boolean isReceiveStart = false;
	private boolean isReceiveAbort = false;
	private boolean isEnd = false;
	private boolean isDready = false;
	private boolean isDabnormal = false;
	
	public boolean isReceiveStart() {
		return isReceiveStart;
	}

	public boolean isReceiveAbort() {
		return isReceiveAbort;
	}

	public boolean isEnd() {
		return isEnd;
	}

	public boolean isDready() {
		return isDready;
	}

	public boolean isDabnormal() {
		return isDabnormal;
	}
	
	public boolean isTestFinished(){
		return isEnd && (isDready || isDabnormal);
	}

	public void reset() {
		isReceiveStart = false;
		isReceiveAbort = false;
		isEnd = false;
		isDready = false;
		isDabnormal = false;
	}

	class MyUdpHandler implements UdpHandler{

		@Override
		public void handler(UdpPacket udpPacket, DatagramSocket datagramSocket) {

			logger.info("the original data:{},{},{}",Arrays.toString(udpPacket.getData()),udpPacket.getRemote(),udpPacket.getTime());
			String msg = new String(udpPacket.getData());
			logger.info("received data:{}",msg);
			
			if (msg.contains("start")) {
				isReceiveStart = true;
				return;
			} else if (msg.contains("abort")) {
				isReceiveAbort = true;
				return;
			}
			
			if(msg.contains("end")) {
				isEnd = true;
			}else if(msg.contains("dready")) {
				isDready = true;
			}else if(msg.contains("dabnormal")) {
				isDabnormal = true;
			}
			
			if(isEnd || isDready || isDabnormal) {
				
				try {
					DatagramPacket p = new DatagramPacket(udpPacket.getData(), udpPacket.getData().length,
//							InetAddress.getByName(udpPacket.getRemote().getIp()), udpPacket.getRemote().getPort()
							InetAddress.getByName(newMachineHost), newMachinePort
							);
					datagramSocket.send(p);
					logger.info("回送数据:{}",msg);
				} catch (IOException  e) {
					logger.error("发送数据:{},失败,error:{}。",msg,e);
				}
			}
			
		}
		
	}
}
相关推荐
嵌入式大圣1 小时前
单片机结合OpenCV
单片机·嵌入式硬件·opencv
陌小呆^O^2 小时前
Cmakelist.txt之win-c-udp-client
c语言·开发语言·udp
日晨难再3 小时前
嵌入式:STM32的启动(Startup)文件解析
stm32·单片机·嵌入式硬件
yufengxinpian3 小时前
集成了高性能ARM Cortex-M0+处理器的一款SimpleLink 2.4 GHz无线模块-RF-BM-2340B1
单片机·嵌入式硬件·音视频·智能硬件
__基本操作__4 小时前
历遍单片机下的IIC设备[ESP--0]
单片机·嵌入式硬件
网易独家音乐人Mike Zhou10 小时前
【卡尔曼滤波】数据预测Prediction观测器的理论推导及应用 C语言、Python实现(Kalman Filter)
c语言·python·单片机·物联网·算法·嵌入式·iot
lantiandianzi18 小时前
基于单片机的多功能跑步机控制系统
单片机·嵌入式硬件
哔哥哔特商务网18 小时前
高集成的MCU方案已成电机应用趋势?
单片机·嵌入式硬件
跟着杰哥学嵌入式18 小时前
单片机进阶硬件部分_day2_项目实践
单片机·嵌入式硬件
dot.Net安全矩阵18 小时前
.NET 通过模块和驱动收集本地EDR的工具
windows·安全·web安全·.net·交互