JAVA 통신 프로 그래 밍 (4) - UDP 통신
UdpImpl 클래스 는 다음 과 같 습 니 다:
package com.zzh.comm;
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.Map;
import org.apache.log4j.Logger;
public class UdpImpl implements CommBuff
{
private Logger logger = Logger.getLogger(Object.class.getName());
private int local_port;
private int dest_port;
private String ip;
private int time_out;
DatagramSocket client = null;
private String fileName = "/udp.properties";
public UdpImpl()
{
Map<String,String> map = new ReadProperties().getPropertiesMap(fileName);
try
{
local_port = Integer.parseInt(map.get("udp_local_port"));
dest_port = Integer.parseInt(map.get("udp_dest_port"));
time_out = Integer.parseInt(map.get("udp_timeout"));
ip = map.get("udp_dest_ip");
}
catch (Exception e)
{
logger.error(e.getMessage());
}
}
@Override
public byte[] readBuff()
{
if(client == null)
{
throw new RuntimeException("clinet is null!");
}
byte[] recvBuf = new byte[1024];
DatagramPacket recvPacket = new DatagramPacket(recvBuf , recvBuf.length);
try
{
client.receive(recvPacket);
}
catch (IOException e)
{
logger.info(e.getMessage());
return new byte[0];
}
byte[] ans = new byte[recvPacket.getLength()];
System.arraycopy(recvPacket.getData(), 0, ans, 0, recvPacket.getLength());
logger.info(" :"+CommUtil.bytesToHex(ans));
return ans;
}
@Override
public void writeBuff(byte[] message)
{
if(client == null)
{
throw new RuntimeException("clinet is null!");
}
try
{
InetAddress addr = InetAddress.getByName(ip);
DatagramPacket sendPacket = new DatagramPacket(message,message.length,addr,dest_port);
client.send(sendPacket);
logger.info(" : "+CommUtil.bytesToHex(message));
}
catch (UnknownHostException e)
{
logger.error(e.getMessage());
}
catch (IOException e)
{
logger.error(e.getMessage());
}
}
@Override
public void open() {
try
{
client = new DatagramSocket(local_port);
client.setSoTimeout(time_out);
if(client != null)
{
logger.info("client open succeed!");
}
}
catch (SocketException e)
{
logger.error(e.getMessage());
}
}
@Override
public void close()
{
if(client != null)
{
client.close();
}
}
@Override
public Object getInfo()
{
return null;
}
}
UdpImpl 은 CommBuff 인터페이스의 각 방법 을 실현 했다.UDP Socket 이 사용 하 는 패 킷 방식 으로 통신 하 는데 이것 은 TCP 방식 과 구분 할 수 있 습 니 다.
다음은 간단 한 공장 모델 을 통 해 바 텀 통신 의 편의 성 을 실현 할 수 있다.
package com.zzh.comm;
public class CommFactory
{
public CommBuff getCommBuff(String properties) throws Exception
{
if(properties.equals("comm_serial"))
{
return new SerialImpl();
}
else if(properties.equals("comm_tcpServer"))
{
return new TcpServerImpl();
}
else if(properties.equals("comm_tcpClient"))
{
return new TcpClientImpl();
}
else if(properties.equals("comm_udp"))
{
return new UdpImpl();
}
else
{
throw new Exception("Communication para error: no found avaliable communication Object instance.");
}
}
}
위의 getCommBuff 방법 은 매개 변수 properties 를 통 해 서로 다른 통신 인터페이스 실현 류 를 초기 화 할 수 있 습 니 다. 그러면 지난번 응용 은 Commbuff 인터페이스 만 호출 하 는 방법 이 고 바 텀 통신 의 디 테 일 과 융합 되 지 않 아 도 프로그램 간 의 결합 성 을 크게 낮 출 수 있 습 니 다.
이 편 은 간단하게 여기까지 논술 하 였 다.그러나 다음은 하나의 프로그램 을 추가 합 니 다. 이 프로그램 은 CommFactory 를 호출 하 는 방법 으로 바 텀 통신 의 인 스 턴 스 를 생 성 합 니 다. 프로그램의 주요 내용 은 전력 업계 의 특정한 통신 규약 (Modbus) 의 실현 입 니 다. 만약 에 비 전력 업계 의 통신 이 라면 프로그램의 세부 사항 을 알 필요 가 없 으 며 어떻게 사용 하 는 지 대충 볼 수 있 습 니 다.
package com.zzh.protocol;
import java.util.Calendar;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import com.zzh.comm.CommBuff;
import com.zzh.comm.CommFactory;
import com.zzh.comm.CommUtil;
import com.zzh.comm.ReadProperties;
import com.zzh.dao.ModbusDao;
import com.zzh.dao.ModbusDaoImpl;
import com.zzh.dao.pojo.ModbusPojo;
public class Modbus {
private CommBuff comm;
private int comm_timeout;
private byte devAddr;
private static int RECV_SIZE = 35;
private static int RECV_INNER_SIZE = 30;
private static int MINUTE=60000;
private volatile boolean refreshFlag = false;
private ModbusPojo modbusPojo;
private ConcurrentLinkedDeque<Byte> deque = new ConcurrentLinkedDeque<Byte>();
private String fileName = "/modbus.properties";
public Modbus()
{
Map<String,String> map = new ReadProperties().getPropertiesMap(fileName);
String comm_way = map.get("modbus_comm_way");
String comm_timeouts = map.get("comm_timeout");
comm_timeout = Integer.parseInt(comm_timeouts);
String devAddrs = map.get("devAddr");
devAddr = Byte.parseByte(devAddrs);
if(comm_way!=null)
{
modbusPojo = new ModbusPojo();
try
{
comm = new CommFactory().getCommBuff(comm_way);
}
catch (Exception e)
{
e.printStackTrace();
}
comm.open();
ExecutorService pool = Executors.newFixedThreadPool(2);
Thread thread1 = new Thread(new readThread());
thread1.setDaemon(true);
Thread thread2 = new Thread(new dbThread());
thread2.setDaemon(true);
pool.execute(thread1);
pool.execute(thread2);
}
else
{
throw new RuntimeException(" ");
}
}
private class readThread implements Runnable
{
@Override
public void run()
{
while(true)
{
byte[] recvBuff = comm.readBuff();
if(recvBuff.length>0)
{
for(int i=0;i<recvBuff.length;i++)
{
deque.add(recvBuff[i]);
}
}
try
{
TimeUnit.MILLISECONDS.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
private class dbThread implements Runnable
{
@Override
public void run()
{
while(true)
{
if(refreshFlag == true)
{
Calendar now = Calendar.getInstance();
if(now.get(Calendar.MINUTE)%5==0)
// if(true)
{
synchronized (modbusPojo)
{
filterModbusPojo();
modbusPojo.setNow(TimeUtil.getDateOfMM(now));
// modbusPojo.setNow(new java.sql.Timestamp(new Date().getTime()));
ModbusDao md = new ModbusDaoImpl();
md.addModbus(modbusPojo);
}
}
}
try
{
TimeUnit.MILLISECONDS.sleep(MINUTE);
// TimeUnit.MILLISECONDS.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
public void filterModbusPojo()
{
modbusPojo.setQua(0);
if(modbusPojo.getEnvTemperature()>ModbusUtil.TEMPERATURE_UP)
{
modbusPojo.setEnvTemperature(ModbusUtil.TEMPERATURE_UP);
System.out.println("getEnvTemperature = "+modbusPojo.getEnvTemperature());
modbusPojo.setQua(1);
}
if(modbusPojo.getEnvTemperature()<ModbusUtil.TEMPERATURE_LOW)
{
modbusPojo.setEnvTemperature(ModbusUtil.TEMPERATURE_LOW);
System.out.println("getEnvTemperature = "+modbusPojo.getEnvTemperature());
modbusPojo.setQua(1);
}
if(modbusPojo.getTemperature()>ModbusUtil.TEMPERATURE_UP)
{
modbusPojo.setTemperature(ModbusUtil.TEMPERATURE_UP);
System.out.println("getTemperature = "+modbusPojo.getTemperature());
modbusPojo.setQua(1);
}
if(modbusPojo.getTemperature()<ModbusUtil.TEMPERATURE_LOW)
{
modbusPojo.setTemperature(ModbusUtil.TEMPERATURE_LOW);
System.out.println("getTemperature = "+modbusPojo.getTemperature());
modbusPojo.setQua(1);
}
if(modbusPojo.getHumidity()>ModbusUtil.HUMIDITY_UP)
{
modbusPojo.setHumidity(ModbusUtil.HUMIDITY_UP);
System.out.println("getHumidity = "+modbusPojo.getHumidity());
modbusPojo.setQua(1);
}
if(modbusPojo.getHumidity()<ModbusUtil.HUMIDITY_LOW)
{
modbusPojo.setHumidity(ModbusUtil.HUMIDITY_LOW);
System.out.println("getHumidity = "+modbusPojo.getHumidity());
modbusPojo.setQua(1);
}
if(modbusPojo.getPressure()>ModbusUtil.PRESSURE_UP)
{
modbusPojo.setPressure(ModbusUtil.PRESSURE_UP);
System.out.println("getPressure = "+modbusPojo.getPressure());
modbusPojo.setQua(1);
}
if(modbusPojo.getPressure()<ModbusUtil.PRESSURE_LOW)
{
modbusPojo.setPressure(ModbusUtil.PRESSURE_LOW);
System.out.println("getPressure = "+modbusPojo.getPressure());
modbusPojo.setQua(1);
}
if(modbusPojo.getIrradiance()>ModbusUtil.IRRADIANCE_UP)
{
modbusPojo.setIrradiance(ModbusUtil.IRRADIANCE_UP);
System.out.println("getIrradiance = "+modbusPojo.getIrradiance());
modbusPojo.setQua(1);
}
if(modbusPojo.getIrradiance()<ModbusUtil.IRRADIANCE_LOW)
{
modbusPojo.setIrradiance(ModbusUtil.IRRADIANCE_LOW);
System.out.println("getIrradiance = "+modbusPojo.getIrradiance());
modbusPojo.setQua(1);
}
if(modbusPojo.getScaIrradiance()>ModbusUtil.IRRADIANCE_UP)
{
modbusPojo.setScaIrradiance(ModbusUtil.IRRADIANCE_UP);
System.out.println("getScaIrradiance = "+modbusPojo.getScaIrradiance());
modbusPojo.setQua(1);
}
if(modbusPojo.getScaIrradiance()<ModbusUtil.IRRADIANCE_LOW)
{
modbusPojo.setScaIrradiance(ModbusUtil.IRRADIANCE_LOW);
System.out.println("getScaIrradiance = "+modbusPojo.getScaIrradiance());
modbusPojo.setQua(1);
}
if(modbusPojo.getDirIrradiance()>ModbusUtil.IRRADIANCE_UP)
{
modbusPojo.setDirIrradiance(ModbusUtil.IRRADIANCE_UP);
System.out.println("getDirIrradiance = "+modbusPojo.getDirIrradiance());
modbusPojo.setQua(1);
}
if(modbusPojo.getDirIrradiance()<ModbusUtil.IRRADIANCE_LOW)
{
modbusPojo.setDirIrradiance(ModbusUtil.IRRADIANCE_LOW);
System.out.println("getDirIrradiance = "+modbusPojo.getDirIrradiance());
modbusPojo.setQua(1);
}
if(modbusPojo.getWindSpeed()>ModbusUtil.UAVG_UP)
{
modbusPojo.setWindSpeed(ModbusUtil.UAVG_UP);
System.out.println("getWindSpeed = "+modbusPojo.getWindSpeed());
modbusPojo.setQua(1);
}
if(modbusPojo.getWindSpeed()<ModbusUtil.UAVG_LOW)
{
modbusPojo.setWindSpeed(ModbusUtil.UAVG_LOW);
System.out.println("getWindSpeed = "+modbusPojo.getWindSpeed());
modbusPojo.setQua(1);
}
if(modbusPojo.getWindDir()>ModbusUtil.VAVG_UP)
{
modbusPojo.setWindDir(ModbusUtil.VAVG_UP);
System.out.println("getWindDir = "+modbusPojo.getWindDir());
modbusPojo.setQua(1);
}
if(modbusPojo.getWindDir()<ModbusUtil.VAVG_LOW)
{
modbusPojo.setWindDir(ModbusUtil.VAVG_LOW);
System.out.println("getWindDir = "+modbusPojo.getWindDir());
modbusPojo.setQua(1);
}
}
public void process()
{
try
{
TimeUnit.MILLISECONDS.sleep(comm_timeout);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
recvProcess();
sendProcess();
}
public void recvProcess()
{
refreshFlag = false;
byte[] recvBuff = new byte[RECV_INNER_SIZE];
while(deque.size()>=RECV_SIZE)
{
Byte first = deque.pollFirst();
if(first == devAddr)
{
Byte second = deque.pollFirst();
if(second == 0x03)
{
Byte third = deque.pollFirst();
if(third == RECV_INNER_SIZE)
{
for(int i=0;i<RECV_INNER_SIZE;i++)
{
recvBuff[i] = deque.pollFirst();
}
deque.pollFirst();
deque.pollFirst();
dealRecvBuff(recvBuff);
}
}
}
}
}
public void dealRecvBuff(byte[] recvBuff)
{
System.out.println(CommUtil.bytesToHex(recvBuff));
refreshFlag = true;
getModbusPojo(recvBuff);
// modbusPojo.print();
}
public void getModbusPojo(byte[] recvBuff)
{
int temp;
synchronized (modbusPojo)
{
for(int i=0;i<recvBuff.length;)
{
switch(i)
{
case 0:
temp = ModbusUtil.getSignedAns(recvBuff, 0, 1);
double envTemperature = temp*0.1;
modbusPojo.setEnvTemperature(envTemperature);
break;
case 2:
temp = ModbusUtil.getSignedAns(recvBuff, 2, 3);
double temperature = temp*0.1;
modbusPojo.setTemperature(temperature);
break;
case 4:
temp = ModbusUtil.getUnsignedAns(recvBuff, 4, 5);
double humidity = temp*0.1;
modbusPojo.setHumidity(humidity);
break;
case 6:
temp = ModbusUtil.getUnsignedAns(recvBuff, 6, 7);
double pressure = temp*0.1;
modbusPojo.setPressure(pressure);
break;
case 8:
temp = ModbusUtil.getUnsignedAns(recvBuff, 8, 9);
modbusPojo.setIrradiance(temp);
break;
case 10:
temp = ModbusUtil.getUnsignedAns(recvBuff, 10, 11);
modbusPojo.setScaIrradiance(temp);
break;
case 12:
temp = ModbusUtil.getUnsignedAns(recvBuff, 12, 13);
modbusPojo.setDirIrradiance(temp);
break;
case 14:
temp = ModbusUtil.getUnsignedAns(recvBuff, 14, 15);
modbusPojo.setWindDir(temp);
break;
case 16:
temp = ModbusUtil.getUnsignedAns(recvBuff, 16, 17);
double windSpeed = temp*0.1;
modbusPojo.setWindSpeed(windSpeed);
break;
case 18:
temp = ModbusUtil.getUnsignedAns(recvBuff, 18, 19);
double windSpeedTwo = temp*0.1;
modbusPojo.setWindSpeedTwo(windSpeedTwo);
break;
case 20:
temp = ModbusUtil.getUnsignedAns(recvBuff, 20, 21);
double windSpeedTen = temp*0.1;
modbusPojo.setWindSpeedTen(windSpeedTen);
break;
case 22:
temp = ModbusUtil.getUnsignedAns(recvBuff, 22, 23);
modbusPojo.setDailyExposure(temp);
break;
case 24:
temp = ModbusUtil.getUnsignedAns(recvBuff, 24, 25);
double totalExposure = temp*0.001;
modbusPojo.setTotalExposure(totalExposure);
break;
case 26:
temp = ModbusUtil.getUnsignedAns(recvBuff, 26, 27);
double scaExposure = temp*0.001;
modbusPojo.setScaExposure(scaExposure);
break;
case 28:
temp = ModbusUtil.getUnsignedAns(recvBuff, 28, 29);
double dirExposure = temp*0.001;
modbusPojo.setDirExposure(dirExposure);
break;
}
i=i+2;
}
}
}
public void sendProcess()
{
byte[] message = new byte[8];
int sendLen = 0;
message[sendLen++] = devAddr;
message[sendLen++] = 0x03;
message[sendLen++] = 0x00;
message[sendLen++] = 0x00;
message[sendLen++] = 0x00;
message[sendLen++] = 0x0F;
byte[] crc = CommUtil.CRC16(message,6);
message[sendLen++] = crc[0];
message[sendLen++] = crc[1];
comm.writeBuff(message);
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.