demo 下载链接https://download.youkuaiyun.com/download/wangzhi291/10242404
首先在src下新建包javafish.clients.opc 将JCustomOpc.properties 拷贝到包中, 然后导入三个jar包
jeasyopc.jar commons-logging-1.1.jar和log4j-1.2.13.jar
在项目下新建一个lib目录,也可以自定义名字和路径,但是在JCustomOpc.properties 配置中能指定这个目录。
将JCustomOpc.dll拷贝到 你定义好的目录下。
写一个测试类,添加以下代码。
public static void main(String[] args) throws InterruptedException {
Opc test = new Opc();
JOpc.coInitialize();
JOpc jopc = new JOpc("localhost", "Matrikon.OPC.Simulation", "JOPC1");
// JOpc jopc = new JOpc("192.168.10.68", "Matrikon.OPC.Simulation.1", "JOPC1");
OpcItem item1 = new OpcItem("Random.ArrayOfReal8", true, "");
// OpcItem item1 = new OpcItem("Random.Int2", true, "");
OpcGroup group = new OpcGroup("group1", true, 1000, 0.0f);
group.addItem(item1);
jopc.addGroup(group);
try {
jopc.connect();
System.out.println("JOPC client is connected...");
}
catch (ConnectivityException e2) {
e2.printStackTrace();
}
try {
jopc.registerGroups();
System.out.println("OPCGroup are registered...");
}
catch (UnableAddGroupException e2) {
e2.printStackTrace();
}
catch (UnableAddItemException e2) {
e2.printStackTrace();
}
synchronized(test) {
test.wait(50);
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
// Synchronous reading of item
int cycles = 100;
int acycle = 0;
while (acycle++ < cycles) {
synchronized(test) {
test.wait(1000);
}
try {
OpcItem responseItem = jopc.synchReadItem(group, item1);
System.out.println(responseItem);
System.out.println(sdf.format(responseItem.getTimeStamp().getTime())+":"+ Variant.getVariantName(responseItem.getDataType()) + ": " + responseItem.getValue());
}
catch (ComponentNotFoundException e1) {
e1.printStackTrace();
}
catch (SynchReadException e) {
e.printStackTrace();
}
}
JOpc.coUninitialize();
}
确保自己机器已经运行了服务端。
如图:
JCustomOpc.properties 和JCustomOpc.dll 目录要准确,不然就容易报错找不到配置文件。