org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss occur when I get zk's child Nodes - apache-zookeeper

the case as follow:
I call client.getChildren().forPath("/path".No problem under normal circumstances.
But if the childNodes is too many,the Exception:org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /path occured.
the code:
RetryNTimes retryNTimes = new RetryNTimes(1, 1000);
CuratorFramework client = CuratorFrameworkFactory.newClient("xx.xx.xx.xx:2181",
50000, 50000, retryNTimes);
client.start();
List<String> childNodes = client.getChildren().forPath("/path");
the zkServer is three node cluster.the version is 3.4.13.
the curator version in my client is 2.12.0
someone do me a favor

finally,I find the source reason.the child nodes is too many.so the packet's length from server is more than client packet's length limit(1024 * 4096).so I set the System properties -Djute.maxbuffer = 10485760.the problem is solved.
the relational code:
public static final int packetLen = Integer.getInteger("jute.maxbuffer",
4096 * 1024);
protected void readLength() throws IOException {
int len = incomingBuffer.getInt();
if (len < 0 || len >= ClientCnxn.packetLen) {
throw new IOException("Packet len" + len + " is out of range!");
}
incomingBuffer = ByteBuffer.allocate(len);
}
private void conLossPacket(Packet p) {
if (p.replyHeader == null) {
return;
}
switch (state) {
case AUTH_FAILED:
p.replyHeader.setErr(KeeperException.Code.AUTHFAILED.intValue());
break;
case CLOSED:
p.replyHeader.setErr(KeeperException.Code.SESSIONEXPIRED.intValue());
break;
default:
p.replyHeader.setErr(KeeperException.Code.CONNECTIONLOSS.intValue());
}
finishPacket(p);
}
the logic as follow:
org.apache.zookeeper.ClientCnxn.SendThread#run; -> clientCnxnSocket.doTransport(to, pendingQueue, outgoingQueue, ClientCnxn.this); -> doIO(pendingQueue, outgoingQueue, cnxn); -> readLength(); -> cleanup(); -> conLossPacket(p)
the Exception:"org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /path" maybe mislead user.

Related

Curator ServiceCacheListener is triggered three times when a service is added

I am learning zookeeper and trying out the Curator framework for service discoveries. However, I am facing a weird issue that I have difficulties to figure out. The problem is when I tried to register an instance via serviceDiscovery, the cacheChanged event of the serviceCache gets triggered three times. When I removed an instance, it is only triggered once, which is the expected behavior. Please see the code below:
public class DiscoveryExample {
private static String PATH = "/base";
static ServiceDiscovery<InstanceDetails> serviceDiscovery = null;
public static void main(String[] args) throws Exception {
CuratorFramework client = null;
try {
// this is the ip address of my VM
client = CuratorFrameworkFactory.newClient("192.168.149.129:2181", new ExponentialBackoffRetry(1000, 3));
client.start();
JsonInstanceSerializer<InstanceDetails> serializer = new JsonInstanceSerializer<InstanceDetails>(
InstanceDetails.class);
serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class)
.client(client)
.basePath(PATH)
.serializer(serializer)
.build();
serviceDiscovery.start();
ServiceCache<InstanceDetails> serviceCache = serviceDiscovery.serviceCacheBuilder()
.name("product")
.build();
serviceCache.addListener(new ServiceCacheListener() {
#Override
public void stateChanged(CuratorFramework curator, ConnectionState state) {
// TODO Auto-generated method stub
System.out.println("State Changed to " + state.name());
}
// THIS IS THE PART GETS TRIGGERED MULTIPLE TIMES
#Override
public void cacheChanged() {
System.out.println("Cached Changed ");
List<ServiceInstance<InstanceDetails>> list = serviceCache.getInstances();
Iterator<ServiceInstance<InstanceDetails>> it = list.iterator();
while(it.hasNext()) {
System.out.println(it.next().getAddress());
}
}
});
serviceCache.start();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("> ");
String line = in.readLine();
} finally {
CloseableUtils.closeQuietly(serviceDiscovery);
CloseableUtils.closeQuietly(client);
}
}
}
AND
public class RegisterApplicationServer {
final static String PATH = "/base";
static ServiceDiscovery<InstanceDetails> serviceDiscovery = null;
public static void main(String[] args) throws Exception {
CuratorFramework client = null;
try {
client = CuratorFrameworkFactory.newClient("192.168.149.129:2181", new ExponentialBackoffRetry(1000, 3));
client.start();
JsonInstanceSerializer<InstanceDetails> serializer = new JsonInstanceSerializer<InstanceDetails>(
InstanceDetails.class);
serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class).client(client).basePath(PATH)
.serializer(serializer).build();
serviceDiscovery.start();
// SOME OTHER CODE THAT TAKES CARES OF USER INPUT...
} finally {
CloseableUtils.closeQuietly(serviceDiscovery);
CloseableUtils.closeQuietly(client);
}
}
private static void addInstance(String[] args, CuratorFramework client, String command,
ServiceDiscovery<InstanceDetails> serviceDiscovery) throws Exception {
// simulate a new instance coming up
// in a real application, this would be a separate process
if (args.length < 2) {
System.err.println("syntax error (expected add <name> <description>): " + command);
return;
}
StringBuilder description = new StringBuilder();
for (int i = 1; i < args.length; ++i) {
if (i > 1) {
description.append(' ');
}
description.append(args[i]);
}
String serviceName = args[0];
ApplicationServer server = new ApplicationServer(client, PATH, serviceName, description.toString());
server.start();
serviceDiscovery.registerService(server.getThisInstance());
System.out.println(serviceName + " added");
}
private static void deleteInstance(String[] args, String command, ServiceDiscovery<InstanceDetails> serviceDiscovery) throws Exception {
// in a real application, this would occur due to normal operation, a
// crash, maintenance, etc.
if (args.length != 2) {
System.err.println("syntax error (expected delete <name>): " + command);
return;
}
final String serviceName = args[0];
Collection<ServiceInstance<InstanceDetails>> set = serviceDiscovery.queryForInstances(serviceName);
Iterator<ServiceInstance<InstanceDetails>> it = set.iterator();
while (it.hasNext()) {
ServiceInstance<InstanceDetails> si = it.next();
if (si.getPayload().getDescription().indexOf(args[1]) != -1) {
serviceDiscovery.unregisterService(si);
}
}
System.out.println("Removed an instance of: " + serviceName);
}
}
I appriciate if anyone can please point out where I am doing wrong and maybe can share some good materials/examples so I can refer to. The official website and the examples on github does not help a lot.

Why is Apache Storm KafkaSpout emitting so many items from Kafka topic?

I'm having issues with Kafka and Storm. I'm not sure at this point if it's a problem with the KafkaSpout config I am setting up, or if I am not ACKing properly or what.
I en-queued 50 items onto my Kafka Topic, but my spout has emitted over 1300 (and counting) tuples. Also, the Spout reports that almost all have "failed." The topology is actually not failing, it's writing to a database successfully, but I just don't know why it is apparently replaying everything so much (if that's what it's doing)
The big question is:
Why is it emitting so many tuples when I only passed 50 to Kafka?
Here is how I am setting up the topology and the KafkaSpout
public static void main(String[] args) {
try {
String databaseServerIP = "";
String kafkaZookeepers = "";
String kafkaTopicName = "";
int numWorkers = 1;
int numAckers = 1;
int numSpouts = 1;
int numBolts = 1;
int messageTimeOut = 10;
String topologyName = "";
if (args == null || args[0].isEmpty()) {
System.out.println("Args cannot be null or empty. Exiting");
return;
} else {
if (args.length == 8) {
for (String arg : args) {
if (arg == null) {
System.out.println("Parameters cannot be null. Exiting");
return;
}
}
databaseServerIP = args[0];
kafkaZookeepers = args[1];
kafkaTopicName = args[2];
numWorkers = Integer.valueOf(args[3]);
numAckers = Integer.valueOf(args[4]);
numSpouts = Integer.valueOf(args[5]);
numBolts = Integer.valueOf(args[6]);
topologyName = args[7];
} else {
System.out.println("Bad parameters: found " + args.length + ", required = 8");
return;
}
}
Config conf = new Config();
conf.setNumWorkers(numWorkers);
conf.setNumAckers(numAckers);
conf.setMessageTimeoutSecs(messageTimeOut);
conf.put("databaseServerIP", databaseServerIP);
conf.put("kafkaZookeepers", kafkaZookeepers);
conf.put("kafkaTopicName", kafkaTopicName);
/**
* Now would put kafkaSpout instance below instead of TemplateSpout()
*/
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout(topologyName + "-flatItems-from-kafka-spout", getKafkaSpout(kafkaZookeepers, kafkaTopicName), numSpouts);
builder.setBolt(topologyName + "-flatItem-Writer-Bolt", new ItemWriterBolt(), numBolts).shuffleGrouping(topologyName + "-flatItems-from-kafka-spout");
StormTopology topology = builder.createTopology();
StormSubmitter.submitTopology(topologyName, conf, topology);
} catch (Exception e) {
System.out.println("There was a problem starting the topology. Check parameters.");
e.printStackTrace();
}
}
private static KafkaSpout getKafkaSpout(String zkHosts, String topic) throws Exception {
//String topic = "FLAT-ITEMS";
String zkNode = "/" + topic + "-subscriber-pipeline";
String zkSpoutId = topic + "subscriberpipeline";
KafkaTopicInZkCreator.createTopic(topic, zkHosts);
SpoutConfig spoutConfig = new SpoutConfig(new ZkHosts(zkHosts), topic, zkNode, zkSpoutId);
spoutConfig.startOffsetTime = kafka.api.OffsetRequest.LatestTime();
// spoutConfig.useStartOffsetTimeIfOffsetOutOfRange = true;
//spoutConfig.startOffsetTime = System.currentTimeMillis();
spoutConfig.scheme = new SchemeAsMultiScheme(new StringScheme());
return new KafkaSpout(spoutConfig);
}
and here is the creation of the topic in case that matters
public static void createTopic(String topicName, String zookeeperHosts) throws Exception {
ZkClient zkClient = null;
ZkUtils zkUtils = null;
try {
int sessionTimeOutInMs = 15 * 1000; // 15 secs
int connectionTimeOutInMs = 10 * 1000; // 10 secs
zkClient = new ZkClient(zookeeperHosts, sessionTimeOutInMs, connectionTimeOutInMs, ZKStringSerializer$.MODULE$);
zkUtils = new ZkUtils(zkClient, new ZkConnection(zookeeperHosts), false);
int noOfPartitions = 1;
int noOfReplication = 1;
Properties topicConfiguration = new Properties();
boolean topicExists = AdminUtils.topicExists(zkUtils, topicName);
if (!topicExists) {
AdminUtils.createTopic(zkUtils, topicName, noOfPartitions, noOfReplication, topicConfiguration, RackAwareMode.Disabled$.MODULE$);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (zkClient != null) {
zkClient.close();
}
}
}
you need to see if messages in the bolt failed.
If they all failed too, you probably didn't ack the message in the bolt, or there is exception in the bolt code.
If bolt messages acked, it's more likely a timeout. Increasing the topology timeout config or the paralisim should fix the problem.

How to use sequence in multi-threaded enviroment

I try to create multiple vertexes in parallel:
public static void main(String[] args) throws InterruptedException {
//create db and seq
ODatabaseDocumentTx db = new ODatabaseDocumentTx("memory:/TestDB");
db.create();
OSequenceLibrary seqLib = db.getMetadata().getSequenceLibrary();
seqLib.createSequence("testSeq",
OSequence.SEQUENCE_TYPE.ORDERED,
new OSequence.CreateParams().setStart(0L).setIncrement(1)
);
OrientGraphFactory factory = new OrientGraphFactory("memory:/TestDB", "admin", "admin").setupPool(1, 8);
//mt
Executor executor = Executors.newFixedThreadPool(8);
CountDownLatch latch = new CountDownLatch(1000);
for (int i = 1; i <= 1000; i++) {
executor.execute(() -> {
OrientGraph g = factory.getTx();
try {
OSequence seq = g.getRawGraph().getMetadata().getSequenceLibrary().getSequence("testSeq");
OrientVertex v = g.addVertex("TestClass");
v.setProperty("seq", seq.next());
latch.countDown();
} finally {
g.shutdown();
}
});
}
latch.await(5, TimeUnit.SECONDS);
System.exit(0);
}
And receive lots of exceptions:
com.orientechnologies.orient.core.exception.OConcurrentModificationException:
Cannot UPDATE the record #7:0 because the version is not the latest.
Probably you are updating an old record or it has been modified by
another user (db=v2 your=v1)
How to use sequence in mt environment properly?
OrientDB is entirely based on an optimistic approach with no or few locks. For this reason you should catch the exception and retry. Example:
OrientGraph g = factory.getTx();
try {
for( int retry = 0; retry < 100; ++retry ){
try {
OSequence seq = g.getRawGraph().getMetadata().getSequenceLibrary().getSequence("testSeq");
OrientVertex v = g.addVertex("TestClass");
v.setProperty("seq", seq.next());
latch.countDown();
break;
} catch( ONeedRetryException e ) {
}
}
} finally {
g.shutdown();
}

Error while compiling jCUDA sample from SDK in eclipse 'Input file not found: JCudaVectorAddKernel.cu'

I am new to jCUDA and java as well. I am trying to compile a vector addition program from NVIDIA samples using eclipse on Redhat Linux.
Steps I followed:
1. Enter: nvcc -ptx JCudaVectorAddKernel.cu -> It generates JCudaVectorAddKernel.ptx file
2. Execute following program:
JCudaVectorAdd.java:
package JCudaVectorAdd;
import static jcuda.driver.JCudaDriver.*;
import java.io.*;
import jcuda.*;
import jcuda.driver.*;
public class JCudaVectorAdd
{
public static void main(String[] args) throws IOException
{
// Enable exceptions and omit all subsequent error checks
JCudaDriver.setExceptionsEnabled(true);
// Create the PTX file by calling the NVCC
String ptxFileName = preparePtxFile("JCudaVectorAddKernel.cu");
// Initialize the driver and create a context for the first device.
cuInit(0);
CUdevice device = new CUdevice();
cuDeviceGet(device, 0);
CUcontext context = new CUcontext();
cuCtxCreate(context, 0, device);
// Load the ptx file.
CUmodule module = new CUmodule();
cuModuleLoad(module, ptxFileName);
// Obtain a function pointer to the "add" function.
CUfunction function = new CUfunction();
cuModuleGetFunction(function, module, "add");
int numElements = 100000;
// Allocate and fill the host input data
float hostInputA[] = new float[numElements];
float hostInputB[] = new float[numElements];
for(int i = 0; i < numElements; i++)
{
hostInputA[i] = (float)i;
hostInputB[i] = (float)i;
}
// Allocate the device input data, and copy the
// host input data to the device
CUdeviceptr deviceInputA = new CUdeviceptr();
cuMemAlloc(deviceInputA, numElements * Sizeof.FLOAT);
cuMemcpyHtoD(deviceInputA, Pointer.to(hostInputA),
numElements * Sizeof.FLOAT);
CUdeviceptr deviceInputB = new CUdeviceptr();
cuMemAlloc(deviceInputB, numElements * Sizeof.FLOAT);
cuMemcpyHtoD(deviceInputB, Pointer.to(hostInputB),
numElements * Sizeof.FLOAT);
// Allocate device output memory
CUdeviceptr deviceOutput = new CUdeviceptr();
cuMemAlloc(deviceOutput, numElements * Sizeof.FLOAT);
// Set up the kernel parameters: A pointer to an array
// of pointers which point to the actual values.
Pointer kernelParameters = Pointer.to(
Pointer.to(new int[]{numElements}),
Pointer.to(deviceInputA),
Pointer.to(deviceInputB),
Pointer.to(deviceOutput)
);
// Call the kernel function.
int blockSizeX = 256;
int gridSizeX = (int)Math.ceil((double)numElements / blockSizeX);
cuLaunchKernel(function,
gridSizeX, 1, 1, // Grid dimension
blockSizeX, 1, 1, // Block dimension
0, null, // Shared memory size and stream
kernelParameters, null // Kernel- and extra parameters
);
cuCtxSynchronize();
// Allocate host output memory and copy the device output
// to the host.
float hostOutput[] = new float[numElements];
cuMemcpyDtoH(Pointer.to(hostOutput), deviceOutput,
numElements * Sizeof.FLOAT);
// Verify the result
boolean passed = true;
for(int i = 0; i < numElements; i++)
{
float expected = i+i;
if (Math.abs(hostOutput[i] - expected) > 1e-5)
{
System.out.println(
"At index "+i+ " found "+hostOutput[i]+
" but expected "+expected);
passed = false;
break;
}
}
System.out.println("Test "+(passed?"PASSED":"FAILED"));
// Clean up.
cuMemFree(deviceInputA);
cuMemFree(deviceInputB);
cuMemFree(deviceOutput);
}
private static String preparePtxFile(String cuFileName) throws IOException
{
int endIndex = cuFileName.lastIndexOf('.');
if (endIndex == -1)
{
endIndex = cuFileName.length()-1;
}
String ptxFileName = cuFileName.substring(0, endIndex+1)+"ptx";
File ptxFile = new File(ptxFileName);
if (ptxFile.exists())
{
return ptxFileName;
}
File cuFile = new File(cuFileName);
if (!cuFile.exists())
{
throw new IOException("Input file not found: "+cuFileName);
}
String modelString = "-m"+System.getProperty("sun.arch.data.model");
String command =
"nvcc " + modelString + " -ptx "+
cuFile.getPath()+" -o "+ptxFileName;
System.out.println("Executing\n"+command);
Process process = Runtime.getRuntime().exec(command);
String errorMessage = new String(toByteArray(process.getErrorStream()));
String outputMessage= new String(toByteArray(process.getInputStream()));
int exitValue = 0;
try
{
exitValue = process.waitFor();
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
throw new IOException(
"Interrupted while waiting for nvcc output", e);
}
if (exitValue != 0)
{
System.out.println("nvcc process exitValue "+exitValue);
System.out.println("errorMessage:\n"+errorMessage);
System.out.println("outputMessage:\n"+outputMessage);
throw new IOException(
"Could not create .ptx file: "+errorMessage);
}
System.out.println("Finished creating PTX file");
return ptxFileName;
}
private static byte[] toByteArray(InputStream inputStream) throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte buffer[] = new byte[8192];
while (true)
{
int read = inputStream.read(buffer);
if (read == -1)
{
break;
}
baos.write(buffer, 0, read);
}
return baos.toByteArray();
}
}
JCudaVectorAddKernel.cu:
extern "C"
__global__ void add(int n, float *a, float *b, float *sum)
{
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i<n)
{
sum[i] = a[i] + b[i];
}
}
Both 'JCudaVectorAddKernel.cu' and 'JCudaVectorAddKernel.java' are in on the same path:
/home/sandeep/workspace1/jCuda/jCudaVectorAdd/src/jCudaVectorAdd
When I execute the program in eclipse it gives me following error:
Exception in thread "main" java.io.IOException: Input file not found: JCudaVectorAddKernel.cu
at JCudaVectorAdd.JCudaVectorAdd.preparePtxFile(JCudaVectorAdd.java:128)
at JCudaVectorAdd.JCudaVectorAdd.main(JCudaVectorAdd.java:20)
Is there anything to do related to the compile command? or ptx/.cu file path?
Please guide me if I am going in the wrong direction.
The sample is trying to compile the PTX file at runtime, and it prints the command that it is trying to execute. When you are compiling the PTX file manually, this may actually not be necessary, and you can change
String ptxFileName = preparePtxFile("JCudaVectorAddKernel.cu");
to
String ptxFileName = "JCudaVectorAddKernel.ptx";
In any case, you may print the file names
File ptxFile = new File(ptxFileName);
System.out.println(ptxFile.getCanonicalPath());
and
File cuFile = new File(cuFileName);
System.out.println(cuFile.getCanonicalPath());
to see whether they match the expected directories. But the PTX file (and the CU file) should probably be located in
/home/sandeep/workspace1/jCuda/jCudaVectorAdd/
(that is, in the "root" directory of your project)

Reading coils using JAMOD

I have written the following program to understand how to use JAMOD to access coils. Unfortunately it is throwing the error -
java.lang.IndexOutOfBoundsException
at java.io.BufferedInputStream.read(Unknown Source)
at java.io.DataInputStream.read(Unknown Source)
at net.wimpi.modbus.io.ModbusTCPTransport.readResponse(ModbusTCPTransport.java:177)
at net.wimpi.modbus.io.ModbusTCPTransaction.execute(ModbusTCPTransaction.java:193)
at TempReader.main(TempReader.java:27)
. x2 more times
.
java.io.EOFException
at java.io.DataInputStream.readUnsignedByte(Unknown Source)
at net.wimpi.modbus.io.BytesInputStream.readUnsignedByte(BytesInputStream.java:153)
at net.wimpi.modbus.io.ModbusTCPTransport.readResponse(ModbusTCPTransport.java:182)
at net.wimpi.modbus.io.ModbusTCPTransaction.execute(ModbusTCPTransaction.java:193)
at TempReader.main(TempReader.java:30)
net.wimpi.modbus.ModbusIOException: Executing transaction failed (tried 3 times)
at net.wimpi.modbus.io.ModbusTCPTransaction.execute(ModbusTCPTransaction.java:197)
at TempReader.main(TempReader.java:30)
In the program line 27 is "trans.execute()". The coil address I am trying to read is 0x7D1 (2001) or channel 0 Data type is 2 word. -
import java.net.*;
import java.io.*;
import net.wimpi.modbus.*;
import net.wimpi.modbus.msg.*;
import net.wimpi.modbus.io.*;
import net.wimpi.modbus.net.*;
import net.wimpi.modbus.util.*;
public class TempReader {
public static void main(String Args[]){
TCPMasterConnection con = null;
ModbusTCPTransaction trans = null;
ReadCoilsRequest rcreq=null;
ReadCoilsResponse rcres=null;
InetAddress addr = null;
int port = Modbus.DEFAULT_PORT;
byte byteArray[]={(byte)192, (byte)168, (byte)0, (byte)182};
try {
addr=InetAddress.getByAddress(byteArray);
con=new TCPMasterConnection(addr);
con.setPort(502);
con.connect();
rcreq=new ReadCoilsRequest(2001, 1);
trans=new ModbusTCPTransaction(con);
trans.setRequest(rcreq);
trans.execute();
rcres=(ReadCoilsResponse)trans.getResponse();
System.out.println("Response : "+rcres.getCoils().toString());
con.close();
}
catch(Exception e){
con.close();
e.printStackTrace();
}
}
}
The error of course repeats 3 times as set in ModbusTCPTransport class (I checked the class source) i.e 3 attempts before exit and program exits.
Where am I going wrong?
My sample Modbus TCP ReadMultipleRegistersRequest.
public static void main(String[] args) {
try {
/**************************************/
//Read And Write Register Sample
int port = Modbus.DEFAULT_PORT;
String refe = "4000";//HEX Address
int ref=Integer.parseInt(refe,16);//Hex to int
int count = 98; //the number Address to read
int SlaveAddr=1;
String astr = "192.168.1.202"; //Modbus Device
InetAddress addr = InetAddress.getByName(astr);
TCPMasterConnection con = new TCPMasterConnection(addr); //the connection
ModbusTCPTransaction trans = null; //the transaction
//1.Prepare the request
/************************************/
ReadMultipleRegistersRequest Rreq = new ReadMultipleRegistersRequest(ref,count);
ReadMultipleRegistersResponse Rres = new ReadMultipleRegistersResponse();
Rreq.setUnitID(SlaveAddr); //set Slave Address
Rres.setUnitID(SlaveAddr); //set Slave Address
//2. Open the connection
con.setPort(port);
con.connect();
con.setTimeout(2500);
//3. Start Transaction
trans = new ModbusTCPTransaction(con);
trans.setRetries(5);
trans.setReconnecting(true);
trans.setRequest(Rreq);
trans.execute();
/*Print Response*/
Rres = (ReadMultipleRegistersResponse) trans.getResponse();
System.out.println("Connected to= "+ astr + con.isConnected() + " / Start Register " + Integer.toHexString(ref));
count=1;
for (int k=0;k<count;k++){
System.out.println("The value READ: " + Rres.getRegisterValue(k));
}
/****************Close Connection**************/
con.close();
System.out.println("\nConnected = " + con.isConnected());
System.exit(0);//edit Java bug error
} catch (Exception ex) {
ex.printStackTrace();
}
}//main
If you want to make slave try this example:
import net.wimpi.modbus.net.*;
import net.wimpi.modbus.procimg.*;
import net.wimpi.modbus.ModbusCoupler;
public class TCPSlaveTest {
public static void main(String[] args) {
try {
/* The important instances and variables */
ModbusTCPListener listener = null;
SimpleProcessImage spi = null;
int port = Modbus.DEFAULT_PORT;
//1. Set port number from commandline parameter
if(args != null && args.length ==1) {
port = Integer.parseInt(args[0]);
}
//2. Prepare a process image
spi = new SimpleProcessImage();
spi.addDigitalOut(new SimpleDigitalOut(true));
spi.addDigitalOut(new SimpleDigitalOut(false));
spi.addDigitalIn(new SimpleDigitalIn(false));
spi.addDigitalIn(new SimpleDigitalIn(true));
spi.addDigitalIn(new SimpleDigitalIn(false));
spi.addDigitalIn(new SimpleDigitalIn(true));
spi.addRegister(new SimpleRegister(251));
spi.addInputRegister(new SimpleInputRegister(45));
//3. Set the image on the coupler
ModbusCoupler.getReference().setProcessImage(spi);
ModbusCoupler.getReference().setMaster(false);
ModbusCoupler.getReference().setUnitID(15);
//4. Create a listener with 3 threads in pool
listener = new ModbusTCPListener(3);
listener.setPort(port);
listener.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}//main
}//class TCPSlaveTest