Let me start off by stating that this is my first post here on stackoverflow. Feel free to point out any mistakes made while posting.
Okay, so the problem at hand is a little weird. I'm currently implementing the FTP protocol for my project, but ran into the following problem. Every time my application has to return the message "227 Entering Passive Mode (<ip1>,<ip2>,<ip3>,<ip4>,<port1>,<port2>)." the connection is terminated. The stack trace being:
java.net.SocketException: Software caused connection abort: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(Unknown Source)
at java.net.SocketOutputStream.write(Unknown Source)
at sun.nio.cs.StreamEncoder.writeBytes(Unknown Source)
at sun.nio.cs.StreamEncoder.implFlushBuffer(Unknown Source)
at sun.nio.cs.StreamEncoder.implFlush(Unknown Source)
at sun.nio.cs.StreamEncoder.flush(Unknown Source)
at java.io.OutputStreamWriter.flush(Unknown Source)
at java.io.BufferedWriter.flush(Unknown Source)
at Server$1.run(Server.java:30)
at java.lang.Thread.run(Unknown Source)
In order to replicate the behaviour I decided to build a prototype which accepts a connection on port 21 and sends the message "227 " after recieving an arbitrary message from the client. This also results in the connection being terminated.
(Prototype Code snippet:)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
public void run() {
ServerSocket server = null;
try {
server = new ServerSocket(21);
} catch (IOException e1) {
e1.printStackTrace();
}
while(true) {
try {
Socket client = server.accept();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = null;
while((line = reader.readLine()) != null) {
writer.write("227 \r\n");
writer.flush();
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}
}
(I'm aware the above code is not the nicest implementation, but is imho sufficiently adequate for representing the problem at hand.)
After some tinkering with the prototype I have figured out that this behaviour only occurs when sending "227 " in conjunction with using port 21 (e.g. using port 4500 works just fine).
Now of course the obvious workaround to this is to avoid using port 21, but i would like to know why i'm experiencing this. Any input on the matter is highly appreciated ;) (just to make sure, i'm using JavaSE-1.7).
Related
I am learning about Sockets in Java and I am only missing how to receive back response from the server.
Following How to send string array object and How to send and receive serialized object in socket channel, I am trying to ask the user to pick as much as he wants out of choices:
1 - 2 - 3 - 4
And then I want to split and send them as an array to a server, where the server should send back the number of choices the user has picked.
For example if the user chose
2 3 4 1 2 3 4 1
Server should return
8
server is sending response fine, but on the client side I get error:
Exception in thread "main" java.net.ConnectException: Connection
refused: connect at java.net.DualStackPlainSocketImpl.connect0(Native
Method) at java.net.DualStackPlainSocketImpl.socketConnect(Unknown
Source) at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source) at
java.net.PlainSocketImpl.connect(Unknown Source) at
java.net.SocksSocketImpl.connect(Unknown Source) at
java.net.Socket.connect(Unknown Source) at
java.net.Socket.connect(Unknown Source) at
java.net.Socket.(Unknown Source) at
java.net.Socket.(Unknown Source) at
ClientClass.main(ClientClass.java:26)
I am not sure why the issue. Any help?
My Client:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Scanner;
public class ClientClass {
public static void main(String args[]) throws IOException, ClassNotFoundException
{
// take order and convert it to array of choices
Scanner myScanner = new Scanner(System.in); // take from user
System.out.println("Enter all your choices seperated by space:");
System.out.println("Choices are: 1- 2- 3- 4");
String orderString = myScanner.next();
orderString += myScanner.nextLine();
String orderArray[] = orderString.split(" ");
// send request to server
Socket mySocket = new Socket("127.0.0.1", 4444); // create a socket
ObjectOutputStream out = new ObjectOutputStream(mySocket.getOutputStream());
out.writeObject(orderArray);
// get response from server
InputStream is = mySocket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " +message);
}
}
My Server:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.SocketChannel;
import java.util.Scanner;
public class ServerClass {
public static void main(String args[]) throws IOException, ClassNotFoundException
{
// receive
ServerSocket myServerSocket = new ServerSocket(4444); // create a server socket
Socket mySimpleSocket = myServerSocket.accept(); // accept requests
ObjectInputStream ois = new ObjectInputStream(mySimpleSocket.getInputStream());
String[] choices = (String[]) ois.readObject();
// send back response
OutputStream os = mySimpleSocket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(choices.length);
System.out.println("Message sent to the client is "+choices.length);
bw.flush();
}
}
server is sending response fine
Rubbish. The server isn't even getting an incoming connection, let alone reading the request, let alone sending a response.
but on the client side I get error:
Exception in thread "main" java.net.ConnectException: Connection refused: connect at
On this evidence the server wasn't even running. Certainly not running in the same host as the client, which is what is required by new Socket("127.0.0.1", 4444).
Why java is showing this output for every port connections And is it require any thing like basic frame or package in java other than these.i am working on basic server client program first is client and second is server.I tried basic code for only connection.but it shows this output every time
import java.io.*;
import java.net.*;
class DateClient
{
public static void main(String args[]) throws Exception
{
Socket soc=new Socket(InetAddress.getLocalHost(),5217);
BufferedReader in=new BufferedReader(new InputStreamReader(soc.getInputStream() ));
System.out.println(in.readLine());
}
}
import java.net.*;
import java.io.*;
import java.util.*;
class DateServer
{
public static void main(String args[]) throws Exception
{
ServerSocket s=new ServerSocket(5217);
while(true)
{
System.out.println("Waiting For Connection ...");
Socket soc=s.accept();
DataOutputStream out=new DataOutputStream(soc.getOutputStream());
out.writeBytes("Server Date: " + (new Date()).toString() + "\n");
out.close();
soc.close();
}
}
}
THIS IS OUTPUT
output:=
Exception in thread "main" java.net.ConnectException: Connection timed out: conn
ect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at DateClient.main(DateClient.java:8)
You are using the DNS resolver to get the local hostname, and you encounter a timeout when connecting to it, so:
either your DNS resolver is configured to a host that is down or filtered by a firewall,
or the DNS resolver resolves the local host name to an IP that is not the one of your server and is down or filtered by a firewall.
These are the two main cases for which you may have such a timeout, instead of a host unreachable or port unreachable error.
So, replace the line:
Socket soc = new Socket(InetAddress.getLocalHost(),5217);
by this one:
Socket soc = new Socket(InetAddress.getLoopbackAddress(), 5217);
to solve your problem.
I am creating a Java HTTP server that checks to make sure a client is not banned before redirecting to the main server. I have already created everything for the server that is needed, I just don't know how to redirect to another port that is running the main server. Here is my code:
package netlyaccesscontrol;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class AllowedCheck {
public static void main(String[] args) {
String line = null;
try {
FileReader reader = new FileReader("Banned.txt");
BufferedReader buffer = new BufferedReader(reader);
ServerSocket s = new ServerSocket(80);
Socket c = s.accept();
String clientIP = c.getInetAddress().toString();
while ((line = buffer.readLine()) != null) {
if (clientIP == line) {
s.close();
} else {
// redirect to main server here
}
}
} catch (FileNotFoundException ex) {
System.out.println("The banned IP address file does not exist.");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
The redirection that you are thinking of is something supported by HTTP and the browsers. There's a specific HTTP response code that tells the caller to redirect and a way to specify it.
Raw sockets are a low-level network protocol that is not going to support redirection as you expect. The most you might be able to do is have this program be a proxy and, upon success, push all incoming data/outgoing responses to/from the ultimate server. But what you have here is by no means going to cut it.
i am new in java... i am trying to read on modbus. PLC is slave device and it is configured well. my java file is unable to read modbus values.here is the code..given below. error is coming at master.init(); method. please help me in this case.
package com.mod4j;
import java.io.File;
import gnu.io.SerialPort;
import com.serotonin.io.serial.SerialParameters;
import com.serotonin.*;
import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.code.DataType;
import com.serotonin.modbus4j.code.RegisterRange;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.locator.BaseLocator;
import com.serotonin.modbus4j.locator.NumericLocator;
import com.serotonin.modbus4j.msg.ReadCoilsRequest;
import com.serotonin.modbus4j.msg.ReadCoilsResponse;
import com.serotonin.modbus4j.msg.ReadDiscreteInputsRequest;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersRequest;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersResponse;
import com.serotonin.modbus4j.msg.ReadInputRegistersRequest;
import com.serotonin.modbus4j.msg.ReadInputRegistersResponse;
import com.serotonin.modbus4j.msg.WriteCoilRequest;
import com.serotonin.modbus4j.msg.WriteCoilResponse;
import com.serotonin.modbus4j.msg.WriteRegistersRequest;
import com.serotonin.modbus4j.msg.WriteRegistersResponse;
import gnu.io.*;
public class Modbus4JTest
{
public static void main(String[] args) throws Exception
{
try
{
SerialParameters params = new SerialParameters();
params.setCommPortId("COM1");
params.setBaudRate(9600);
params.setDataBits(8);
params.setStopBits(1);
params.setParity(0);
ModbusFactory modbusFactory = new ModbusFactory();
ModbusMaster master = modbusFactory.createRtuMaster(params);
master.setTimeout(100);
master.setRetries(3);
byte [] RIR,RHR,RDI,RCR;
int slaveId=1;
int startOffset=0;
int numberOfRegisters=10;
int numberOfBits=10;
try
{
master.init();
while (true)
{
ReadInputRegistersRequest reqRIR = new ReadInputRegistersRequest(slaveId, startOffset, numberOfRegisters);
System.out.println("ReadInputRegistersRequest reqRIR =" +reqRIR);
ReadInputRegistersResponse resRIR = (ReadInputRegistersResponse) master.send(reqRIR);
RIR = resRIR.getData();
System.out.println("InputRegisters :" + RIR);
ReadHoldingRegistersRequest reqRHR = new ReadHoldingRegistersRequest(slaveId, startOffset, numberOfRegisters);
ReadHoldingRegistersResponse resRHR = (ReadHoldingRegistersResponse) master.send(reqRHR);
RHR=resRHR.getData();
System.out.println("HoldingRegister :" + RHR);
ReadDiscreteInputsRequest reqRDI= new ReadDiscreteInputsRequest(slaveId, startOffset, numberOfBits);
ReadCoilsResponse resRDI = (ReadCoilsResponse) master.send(reqRDI);
RDI=resRDI.getData();
System.out.println("DiscreteInput :" + RDI);
ReadCoilsRequest reqRCR = new ReadCoilsRequest(slaveId, startOffset, numberOfBits);
ReadCoilsResponse resRCR = (ReadCoilsResponse) master.send(reqRCR);
RCR=resRCR.getData();
System.out.println("CoilResponce :" + RCR);
short[] sdata = null;
WriteRegistersRequest reqWR = new WriteRegistersRequest(slaveId, startOffset, sdata);
WriteRegistersResponse resWR = (WriteRegistersResponse) master.send(reqWR);
int writeOffset = 0;
boolean writeValue = true;
WriteCoilRequest reqWC = new WriteCoilRequest(slaveId, writeOffset, writeValue);
WriteCoilResponse resWC = (WriteCoilResponse) master.send(reqWC);
Thread.sleep(1000);
}//end while
}//end try
catch (Exception e)
{
e.printStackTrace();
}//end catch
finally
{
master.destroy();
}//end finally
}//end try
catch (Exception e)
{
e.printStackTrace();
}//end catch
}// end main
}//end class Modbus4JTest
this is java file i am running.
and here are the error i have got after compiling..
please suggest what went wrong and please correct me at ...
is there any step by step tutorial or any demo video please give me link at
ayyaz.nadaf#gmail.com
Exception in thread "main" java.lang.NoClassDefFoundError:
jssc/SerialPortException
at com.serotonin.io.serial.SerialUtils.openSerialPort(SerialUtils.java:94)
at com.serotonin.modbus4j.serial.SerialMaster.init(SerialMaster.java:58)
at com.serotonin.modbus4j.serial.rtu.RtuMaster.init(RtuMaster.java:45)
at com.mod4j.Modbus4JTest.main(Modbus4JTest.java:58)
Caused by: java.lang.ClassNotFoundException: jssc.SerialPortException
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 4 more
It appears you're using Modbus4J. It is based on jSSC (Java Simple Serial Connector) for serial communication, so make sure that jSSC is found while compiling (you may need to download it separately, since you're getting a ClassNotFoundException related to a jSSC class).
I don't know about any tutorial but I may suggest you to take a look at the Modbus4J forum archive. Here's a simple Modbus RTU example.
I tried this code from this site server client code
It worked perfect on my machine,I first ran the server code then the client code.
And I got the time.
I tried putting the server side code on to another PC and running it on eclipse there,similarly I tried running client side code from eclipse on my side but wasn't successful.
It gave me the following error:
Exception in thread "main" java.net.BindException: Cannot assign requested address: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method)
at java.net.DualStackPlainSocketImpl.socketBind(Unknown Source)
at java.net.AbstractPlainSocketImpl.bind(Unknown Source)
at java.net.PlainSocketImpl.bind(Unknown Source)
at java.net.ServerSocket.bind(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at sample.servertime.main(servertime.java:13)
Am I doing it correct or is it wrong what I am doing.Need help.
Here are the 2 codes.
// Date Client
import java.io.*;
import java.net.*;
class DateClient
{
publicstaticvoid main(String args[]) throws Exception
{
Socket soc=new Socket(InetAddress.getLocalHost(),5217);
BufferedReader in=new BufferedReader(
new InputStreamReader(
soc.getInputStream()
)
);
System.out.println(in.readLine());
}
}
// Date Server
import java.net.*;
import java.io.*;
import java.util.*;
class DateServer
{
publicstaticvoid main(String args[]) throws Exception
{
InetAddress locIP = InetAddress.getByName("192.168.1.21");
ServerSocket s= new ServerSocket(5217, 0, locIP);
while(true)
{
System.out.println("Waiting For Connection ...");
Socket soc=s.accept();
DataOutputStream out=new DataOutputStream(soc.getOutputStream());
out.writeBytes("Server Date" + (new Date()).toString() + "\n");
out.close();
soc.close();
}
}
}
In the server part you've hard coded the ip address for the server:
InetAddress locIP = InetAddress.getByName("192.168.1.21");
ServerSocket s= new ServerSocket(5217, 0, locIP);
When you run it on the other machine the address will be different and therefore it can't be bound unless you change it.
You could change it to bind to all addresses like:
ServerSocket s = new ServerSocket(5217);
Also, the client will always try to connect to the local machine:
Socket soc=new Socket(InetAddress.getLocalHost(),5217);
So if you want to have the client connect to a server on another machine InetAddress.getLocalHost()has to be changed to the address of the server.