I have a problem with the connection through ethernet modbus tcp.
I insert in to AndroidManifest the permission:
And i create task or connecting and reading Modbus.
I use jamod library.
When I start the application gives me a connection failed error.
This my code that i use:
class Task implements Runnable {
#
Override
public void run() {
try {
ReadMultipleRegistersResponse result = null;
//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.0.18"; //Modbus Device
InetAddress addr = InetAddress.getByName(astr);
TCPMasterConnection con = new TCPMasterConnection(addr);
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();
} catch (ModbusSlaveException me) {
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (java.lang.Exception e) {;
e.printStackTrace();
}
}
}
Where am I doing wrong ?
Follow the steps
Check your slave is working
Check your device of slave that have the same network with the master
Check your port setting of security (default 502)
Related
I am implementing an FTP server in Java for a project. I can start the server but when I try to connect with a client it is stuck on "waiting for welcome message". I've looked at several examples but I'm not sure where I'm going wrong. Here is the class I have. I will eventually break some of this out into other methods.
The user parameters have been cleared for the purposes of this post.
public class FTPServer {
final int PORT = 2221;
String userfile = "";
String username="";
String password = ""
String homedir ="";
private FtpServer server=null;
public FTPServer() {}
public FTPServer(final String ipaddress, final int port){
FtpServerFactory serverFactory = new FtpServerFactory();
ListenerFactory listenerfactory = new ListenerFactory();
listenerfactory.setDataConnectionConfiguration(
new DataConnectionConfigurationFactory().createDataConnectionConfiguration());
ConnectionConfigFactory connection = new ConnectionConfigFactory();
connection.setMaxLoginFailures(10);
connection.setLoginFailureDelay(5);
connection.setAnonymousLoginEnabled(false);
// set the ip address of the listener
listenerfactory.setServerAddress(ipaddress);
// set the port of the listener
if (port == 0)
{ listenerfactory.setPort(PORT);}
else {listenerfactory.setPort(port);
// replace the default listener
serverFactory.addListener("default", listenerfactory.createListener());
serverFactory.setConnectionConfig(connection.createConnectionConfig());
}
PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
userManagerFactory.setFile(new File(userfile));
userManagerFactory.setPasswordEncryptor(new SaltedPasswordEncryptor());
UserManager um = userManagerFactory.createUserManager();
BaseUser user = new BaseUser();
user.setName(username);
user.setPassword(password);
user.setHomeDirectory(homedir);
try {
um.save(user);
} catch (FtpException e1) {
// TODO Auto-generated catch block
this.StopServer();
e1.printStackTrace();
}
serverFactory.setUserManager(um);
server = serverFactory.createServer();
}
public void StopServer(){ this.server.stop(); }
public void StartServer()
{
try {
server.start();
} catch (FtpException e) {
// handle this eventually, good enough for testing now
e.printStackTrace();
}
}
Here is the code that creates the server and starts and stops it
final int port = 0;
final String ipaddress = "";
FTPServer server = new FTPServer(ipaddress,port);
server.StartServer();
server.StopServer();
I'd say that FtpServer.Start only starts listening on the incoming port. It does not block. You kill the server immediately afterwards by calling .Stop.
You have to wait in your code explicitly to keep the server running.
server.StartServer();
Thread.sleep(Long.MAX_VALUE);
My goal here is to make a simple HTTP proxy that can perform GET/POST requests, trying to learn about Java Sockets. Would be appreciated if anyone can point me in that direction.
// This example is from _Java Examples in a Nutshell_. (http://www.oreilly.com)
// Copyright (c) 1997 by David Flanagan
// This example is provided WITHOUT ANY WARRANTY either expressed or implied.
// You may study, use, modify, and distribute it for non-commercial purposes.
// For any commercial use, see http://www.davidflanagan.com/javaexamples
import java.io.*;
import java.net.*;
/**
* This class implements a simple single-threaded proxy server.
**/
public class SimpleProxyServer {
/** The main method parses arguments and passes them to runServer */
public static void main(String[] args) throws IOException {
try {
// Check the number of arguments
if (args.length != 3)
throw new IllegalArgumentException("Wrong number of arguments.");
// Get the command-line arguments: the host and port we are proxy for
// and the local port that we listen for connections on
String host = args[0];
int remoteport = Integer.parseInt(args[1]);
int localport = Integer.parseInt(args[2]);
// Print a start-up message
System.out.println("Starting proxy for " + host + ":" + remoteport +
" on port " + localport);
// And start running the server
runServer(host, remoteport, localport); // never returns
}
catch (Exception e) {
System.err.println(e);
System.err.println("Usage: java SimpleProxyServer " +
"<host> <remoteport> <localport>");
}
}
/**
* This method runs a single-threaded proxy server for
* host:remoteport on the specified local port. It never returns.
**/
public static void runServer(String host, int remoteport, int localport)
throws IOException {
// Create a ServerSocket to listen for connections with
ServerSocket ss = new ServerSocket(localport);
// Create buffers for client-to-server and server-to-client communication.
// We make one final so it can be used in an anonymous class below.
// Note the assumptions about the volume of traffic in each direction...
final byte[] request = new byte[1024];
byte[] reply = new byte[4096];
// This is a server that never returns, so enter an infinite loop.
while(true) {
// Variables to hold the sockets to the client and to the server.
Socket client = null, server = null;
try {
// Wait for a connection on the local port
client = ss.accept();
// Get client streams. Make them final so they can
// be used in the anonymous thread below.
final InputStream from_client = client.getInputStream();
final OutputStream to_client= client.getOutputStream();
// Make a connection to the real server
// If we cannot connect to the server, send an error to the
// client, disconnect, then continue waiting for another connection.
try { server = new Socket(host, remoteport); }
catch (IOException e) {
PrintWriter out = new PrintWriter(new OutputStreamWriter(to_client));
out.println("Proxy server cannot connect to " + host + ":" +
remoteport + ":\n" + e);
out.flush();
client.close();
continue;
}
// Get server streams.
final InputStream from_server = server.getInputStream();
final OutputStream to_server = server.getOutputStream();
// Make a thread to read the client's requests and pass them to the
// server. We have to use a separate thread because requests and
// responses may be asynchronous.
Thread t = new Thread() {
public void run() {
int bytes_read;
try {
while((bytes_read = from_client.read(request)) != -1) {
to_server.write(request, 0, bytes_read);
to_server.flush();
}
}
catch (IOException e) {}
// the client closed the connection to us, so close our
// connection to the server. This will also cause the
// server-to-client loop in the main thread exit.
try {to_server.close();} catch (IOException e) {}
}
};
// Start the client-to-server request thread running
t.start();
// Meanwhile, in the main thread, read the server's responses
// and pass them back to the client. This will be done in
// parallel with the client-to-server request thread above.
int bytes_read;
try {
while((bytes_read = from_server.read(reply)) != -1) {
to_client.write(reply, 0, bytes_read);
to_client.flush();
}
}
catch(IOException e) {}
// The server closed its connection to us, so close our
// connection to our client. This will make the other thread exit.
to_client.close();
}
catch (IOException e) { System.err.println(e); }
// Close the sockets no matter what happens each time through the loop.
finally {
try {
if (server != null) server.close();
if (client != null) client.close();
}
catch(IOException e) {}
}
}
}
}
Code obtained from http://examples.oreilly.com/jenut/SimpleProxyServer.java
I was wondering how I would be able to extract the HOSTNAME from the inputstream and use that information extracted to pass to the method below.
try { server = new Socket(host, remoteport); }
catch (IOException e) {
PrintWriter out = new PrintWriter(new OutputStreamWriter(to_client));
out.println("Proxy server cannot connect to " + host + ":" +
remoteport + ":\n" + e);
out.flush();
client.close();
continue;
}
I've tried creating a method that converts the InputStream into a String format but it seems to make the program get stuck after assigning it to the variable. (Tried something like this over here - Read/convert an InputStream to a String)
You can create a separate ByteArrayOutputStream to get the information from the InputStream.
...
final OutputStream to_client= client.getOutputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
...
And then in the while loop you can write to baos as well
...
while((bytes_read = from_server.read(reply)) != -1) {
to_client.write(reply, 0, bytes_read);
to_client.flush();
baos.write(reply, 0, bytes_read);
}
baos.flush();
...
And you can finally get the string from baos.
String requestString = new String(baos.toByteArray());
Then, you can search the Host header by doing this:
String[] headers = requestString.split("\n");
for (int i = 0; i < headers.length; i++) {
if (headers[i].startsWith("Host")) {
String[] hostHeader = headers[i].split(":");
if (hostHeader.length > 1) {
host = hostHeader[1];
}
}
}
I'm trying create a telnet client(apache) connection to global IP address.
If I use something like below,I can could establish the connection.
private TelnetClient telnet = new TelnetClient();
telnet.connect("172.xx.xxx.xx", port);
However writing it something like below,I get "connection refused error".
private TelnetClient telnet = new TelnetClient();
String host = "172.xx.xxx.xx";
telnet.connect(host, port);
Any suggestion?(i could not find same error in forums, also I am new at asking questions :) )
here is my full code;
public void connectionCreater(String host, int port,String uID,String pass,
String account, String password) {
try {
//telnet.connect("172.xx.xxx.xx", port); this is works.
telnet.connect(host, port);
out = new PrintWriter(telnet.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
telnet.getInputStream()));
if (readUntilThenExecute("login: ", uID + "\r")) {
if (readUntilThenExecute("Password: ", pass + "\r")) {
if (readUntilThenExecute("Enter User Name", account)) {
if (readUntilThenExecute("Enter Password", password)) {
//to do stuff }
}
}
}
} catch (IOException e) {
out.close();
try {
in.close();
} catch (IOException y) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public boolean readUntilThenExecute(String word, String command) {
try {
String result1 = "";
char[] incoming = new char[2048];
boolean check = true;
while (check) {
int lenght = in.read(incoming);
result1 = String.copyValueOf(incoming, 0, lenght);
System.out.println(result1);
if (result1.contains(word)) {
out.println(command);
check = false;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
1.Install telnet use this command in terminal(Applications/Accessories/Terminal):
sudo apt-get install xinetd telnetd
2.Edit /etc/inetd.conf using your favourite file editor with root permission,add this line:
telnet stream tcp nowait telnetd /usr/sbin/tcpd /usr/sbin/in.telnetd
3.Edit /etc/xinetd.conf,make its content look like following:
# Simple configuration file for xinetd
#
# Some defaults, and include /etc/xinetd.d/
defaults
{
# Please note that you need a log_type line to be able to use log_on_success
# and log_on_failure. The default is the following :
# log_type = SYSLOG daemon info
instances = 60
log_type = SYSLOG authpriv
log_on_success = HOST PID
log_on_failure = HOST
cps = 25 30
}
4.You can change telnet port number by edit /etc/services with this line:
telnet 23/tcp
5.If you’re not satisfied with default configuration.Edit etc/xinetd.d/telnet, add following:
# default: on
# description: The telnet server serves telnet sessions; it uses
# unencrypted username/password pairs for authentication.
service telnet
{
disable = no
flags = REUSE
socket_type = stream
wait = no
user = root
server = /usr/sbin/in.telnetd
log_on_failure += USERID
}
add these lines as you like:
only_from = 192.168.120.0/24 #Only users in 192.168.120.0 can access to
only_from = .bob.com #allow access from bob.com
no_access = 192.168.120.{101,105} #not allow access from the two IP.
access_times = 8:00-9:00 20:00-21:00 #allow access in the two times
......
6.Use this command to start telnet server:
sudo /etc/init.d/xinetd start
Given this:
. . .
ServerSocket serverSocket = new ServerSocket(1111);
while (helperSockets.size() < Common.NUM_HELPERS) {
Socket helperSocket = serverSocket.accept();
. . .
This throws the exception:
new Socket("localhost", 1111, InetAddress.getLocalHost(), localPort);
Exception:
java.net.ConnectException: connect: Address is invalid on local machine, or port is not valid on remote machine
I'm trying to use this constructor to set the local port, so what am I doing wrong? Source below.
The constructor creates a thread that listens for clients via ServerSockets, while trying to connect to other clients. This client tries to connect with itself for testing. The problem is encountered upon first iteration of the for loop.
public class DisSemHelper extends Thread {
private int id;
private int semaphore;
private Clock clock;
private Vector<Socket> helperSockets;
private int localPort;
private int receivedSender;
private String receivedOperation;
private int receivedTimestamp;
/**
*/
public DisSemHelper(int id) {
this.id = id;
this.semaphore = 0;
this.clock = new Clock();
this.helperSockets = new Vector<Socket>();
this.receivedSender = -1;
this.receivedOperation = null;
this.receivedTimestamp = -1;
this.localPort = Common.portMap.get(id);
new ConnectionListener().start();
/* Create and store connections to all helpers */
for (int i=0; helperSockets.size() < Common.NUM_HELPERS; i++) {
Socket helperSocket = null;
// String portKey = "STREET_" + i;
/* Wait until target street socket is ready. Retry every second. */
Exception e = new ConnectException();
while (helperSocket == null) {
try {
Thread.sleep(1000);
helperSocket = new Socket("localhost", 2222, InetAddress.getLocalHost(), localPort);
} catch (ConnectException ce) {
e = ce;
e.printStackTrace();
} catch (UnknownHostException uhe) {
uhe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (InterruptedException ie) {
e.printStackTrace();
}
}
int remotePort = helperSocket.getPort();
int connectedHelperID = Common.portMap.indexOf(remotePort);
if (this.helperSockets.size() <= connectedHelperID) {
this.helperSockets.add(helperSocket);
System.out.println("Helper " + id + " added socket from outgoing: local port: " + helperSocket.getLocalPort() + " remote port: " + helperSocket.getPort());
}
}
System.out.println(this.helperSockets);
}
private class ConnectionListener extends Thread {
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(2222);
/* Listen for connections from other helpers */
while (helperSockets.size() < Common.NUM_HELPERS) {
Socket helperSocket = serverSocket.accept();
// TODO Will indexof int in list of Integers work?
int remotePort = helperSocket.getPort();
int connectedHelperID = Common.portMap.indexOf(remotePort);
// TODO Does this really work?
if (connectedHelperID == -1) {
helperSockets.add(helperSocket);
System.out.println("Helper " + id + " added socket from incoming: local port: " + helperSocket.getLocalPort() + " remote port: " + helperSocket.getPort());
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This is a WAG, but I'd try the other constructors in Socket.
Try new Socket(INetAddress.getLocalHost(), "111");
See:
http://ashishmyles.com/tutorials/tcpchat/index.html
Can you make a simple test-case and post the source? That'll help us troubleshoot this better.
new Socket("localhost", 1111, InetAddress.getLocalHost(), localPort);
What exactly are you trying to do here? Why do you need to define what local host/port pair to use locally? A client should normally just specify the remote host/port and let the OS pick the local port. This is perhaps the problem.
Not a true solution, but I ended up working around setting the local port (because nobody seems to like that idea).
i'm working with an example of client-server programm on Java. I faced such a problem:
I start the server with 8080 port and a localhost, than I start a client and make a request. As soon as the request done both programms close theri sockets, so i can't repeat my actions. How can i use the same client and the same server to make more than one request?
public class Network extends Thread
{
MasterEdit ME = new MasterEdit();
private Socket _socket;
InputStream is; //Data streams
OutputStream os;
/**
* Network class constructor
*/
public Network(int port, int backlog, InetAddress address)
{
//We create an object of SocketFactory
SocketFactory sf = new SocketFactory();
//Save server socket
ServerSocket ss = null;
try
{
if(address == null) //If there is no host
{
if(backlog <= 0) //If backlog is not given we create it with port
{ ss = sf.createServerSocket(port);
System.out.println("Success");
}
else
ss = sf.createServerSocket(port, backlog); //If backlog is given we just create it
}
else
ss = sf.createServerSocket(port, backlog, address); //If everything is given we create it using data
}
catch(Exception e)
{
//Exception with creation of socket
System.err.println("Failed open server socket");
System.exit(1); //Stop program and send 1 as a exception-code
}
while(true) //Listening to the socket
{
try
{
StartThread(ss.accept()); //If client has connected we send him to the daemon
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
/**
* Start daemon-tool when client has connected
*/
private void StartThread(Socket ss)
{
_socket = ss; //initializing of global variable
setDaemon(true); //anounce that new potok is daemon
setPriority(NORM_PRIORITY); //set the priority
start(); //Start it
}
#Override
public void run()
{
byte buffer[] = new byte[64*1024]; //buffer in 64 kb
try
{
is = _socket.getInputStream();
os = _socket.getOutputStream(); //Initializing the output stream to a client
String toClient = SearchRequest(new String(buffer, 0, is.read(buffer)));
os.write(toClient.getBytes()); //Sending an answer
}
catch(Exception e)
{
e.printStackTrace();
}
}
private String SearchRequest(String request)
{
String info = ""; //Initializing of a variable
if(request.equalsIgnoreCase("info")) //Check the request
{
//Adding data
info += "Virtual Machine Information (JVM)n";
info += "JVM Name: " + System.getProperty("java.vm.name")+"n";
info += "JVM installation directory: " + System.getProperty("java.home")+"n";
info += "JVM version: " + System.getProperty("java.vm.version")+"n";
info += "JVM Vendor: " + System.getProperty("java.vm.vendor")+"n";
info += "JVM Info: " + System.getProperty("java.vm.info")+"n";
return info; //Give the answer
}
if(request.charAt(0)=='0') {
StringTokenizer rm = new StringTokenizer(request, " \t\n\r,:");
rm.nextToken();
ME.MasterDell(Double.parseDouble(rm.nextToken()), Double.parseDouble(rm.nextToken()), Double.parseDouble(rm.nextToken()), Double.parseDouble(rm.nextToken()));
return "Successfully deleted";
}
if(request.charAt(0)=='1'){
StringTokenizer temp = new StringTokenizer(request, " \t\n\r,:");
temp.nextToken();
ME.MasterAdd(Double.parseDouble(temp.nextToken()), Double.parseDouble(temp.nextToken()), Double.parseDouble(temp.nextToken()), Double.parseDouble(temp.nextToken()), Double.parseDouble(temp.nextToken()), Double.parseDouble(temp.nextToken()), temp.nextToken());
return "Successfully added";
}
this.ClostIt();
return "Bad request"; //bad request
}
public void ClostIt() {
try {
is.close();
os.close();
_socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
It's server part. It usess SocketFactory class but mainly it just creates a socket in the begining. In main programm i call new Network(PORT, BACKLOG, InetAddress.getByName(host));
I am guessing in your server program you don't have a loop but rather something like this:
public static void main( String args[] ) {
ServerSocket server = new ServerSocket(...);
Socket con = server.accept();
//process the client connection ...
//done, exit!
}
rather than
public static void main( String args[] ) {
ServerSocket server = new ServerSocket(...);
Socket con = null;
while( condition /* e.g. shutdown server message received */ ) {
con = server.accept();
//process the client connection ...
//then keep waiting for the next request
}
//done, exit!
}
Bear in mind the above sample only processes one client at a time! you will need to step into multi-threading for processing simultaneous clients.
This is a good starter for a multi threaded server
http://www.kieser.net/linux/java_server.html
Mark