I was executing a socket program.The program is to, just echo the user input ,
by the server .ie if the user gives input as Apple the server reply should be Apple.
But the problem now i am facing is, the server is sending a message(instead of Apple ) which used to be the Banner Message that we get when we login to the server.Once the banner message is over ,the following error gets displayed :
Exception in thread "main" java.net.SocketException: Software caused connection abort: recv failed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at EchoClient.main(EchoClient.java:69)
Following is my code :
import java.net.*;
import java.io.*;
public class EchoClient
{
public static void main(String[] args) throws IOException
{
Socket echosocket = null;
PrintWriter out =null;
BufferedReader in=null;
//establish the socket connection between the client and the server
// open a PrintWriter and a BufferedReader on the socket:
try
{
echosocket = new Socket("ltesol1.comm.mot.com",22);
out=new PrintWriter(echosocket.getOutputStream(),true);
in=new BufferedReader(new InputStreamReader(echosocket.getInputStream()));
}
catch(UnknownHostException e)
{
System.err.print("Unable to find the host dkc678-01");
System.exit(1);
}
catch(IOException e)
{
System.err.print("No IO for host dkc678-01");
System.exit(1);
}
BufferedReader stdIn=new BufferedReader(new InputStreamReader(System.in));
String userInput;
while((userInput =stdIn.readLine())!= null )
{
out.println(userInput);
System.out.println("echo :" + in.readLine());
}
out.close();
in.close();
stdIn.close();
echosocket.close();
}
}
If you want too connect to a SSH-Server, you have to use the ssh-protocol: http://javassh.org
You should find the sources of a ssh-client there.
Can you please comment on my suggestion that another service (ie sshd/telnet server) is listening to port 22 on the server side? Or otherwise give us the server code?
Port 22 is usually used for ssh which is an encrypted connection. You can't use a plain text stream.
In either case, the server is disconnecting the connection. You need to find out why it is doing that.
Related
I am building a swing application to download multiple files over the internet and save to a windows fileshare. I have used SwingWroker which internally uses the ExecutorService which internally queues them and downloads 10 at a time, but for some reason after downloading say 2 - 3 MB of file it stops and moves to next downloading file, They are downloaded in a batch of 10 as SwingWorker has fixed it in number of Threads for the Executor Service.
I have to write these files in a windows file share and I am using nio.FileChannels to do that. There are files ranging from 50-60 each weighing around 300MB - 500MB. The file links are located on a webpage to where I get to by login in using credentials on a login page(with a post request) over the internet before that I specify CookieHandler.setDefault(new CookieManager()) at the beginning and so it behaves like a browser to me.
Another observation is when I download them locally (not to a windows server share) they do work fine.
This is the code I am using
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import javax.swing.SwingWorker;
public class DownloadProcess extends SwingWorker<Boolean, String> {
private String urlPath, filePath;
public DownloadProcess(String urlPath, String filePath){
this.urlPath = urlPath;
this.filePath = filePath;
}
#Override
protected Boolean doInBackground() {
boolean taskState = true;
URLConnection httpConn = null;
ReadableByteChannel readableByteChannel = null;
FileOutputStream fileOutputStream = null;
FileChannel fileOutputChannel = null;
try{
//String filePath = "\\\\fileshare.server\\xyz.txt";
//String urlPath = "http://example.com/anyBigFile.1GB.docx";
File localFile = new File(filePath);//File share
boolean itsThere = localFile!=null && localFile.exists();
long done = itsThere ? localFile.length() : 0;
URL url = new URL(urlPath);
httpConn = url.openConnection();
httpConn.setRequestProperty("Connection", "keep-alive");
if(itsThere) {
httpConn.setRequestProperty("Range","bytes="+done+"-");
}
readableByteChannel = Channels.newChannel(httpConn.getInputStream());
fileOutputStream = itsThere ? new FileOutputStream(filePath) : new FileOutputStream(filePath,true);
fileOutputChannel = fileOutputStream.getChannel();
for (long position = done, size = httpConn.getContentLength(); position < size && !isCancelled(); ) {
position += fileOutputChannel.transferFrom(readableByteChannel, position, 1 << 16);
}
//done
}catch(Exception e){
taskState = false;
e.printStackTrace();
}finally{
//close streams conns etc
}
return taskState;
}
}
This is the error stack trace that I get after 5 - 10 mins of download
/*
javax.net.ssl.SSLException: Connection has been shutdown: javax.net.ssl.SSLException: java.net.SocketException: Connection reset
at sun.security.ssl.SSLSocketImpl.checkEOF(Unknown Source)
at sun.security.ssl.AppInputStream.read(Unknown Source)
at java.io.BufferedInputStream.read1(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
at sun.net.www.MeteredStream.read(Unknown Source)
at java.io.FilterInputStream.read(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(Unknown Source)
at java.nio.channels.Channels$ReadableByteChannelImpl.read(Unknown Source)
at com.objects.DownloadByteChannel.read(DownloadByteChannel.java:117)
at sun.nio.ch.FileChannelImpl.transferFromArbitraryChannel(Unknown Source)
at sun.nio.ch.FileChannelImpl.transferFrom(Unknown Source)
at com.core.DownloadTask.doInBackground(DownloadTask.java:154)
at com.core.DownloadTask.doInBackground(DownloadTask.java:59)
at com.util.ZSwingWorker$1.call(ZSwingWorker.java:286)
at java.util.concurrent.FutureTask.run(Unknown Source)
at com.util.ZSwingWorker.run(ZSwingWorker.java:325)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: javax.net.ssl.SSLException: java.net.SocketException: Connection reset
at sun.security.ssl.Alerts.getSSLException(Unknown Source)
at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
at sun.security.ssl.SSLSocketImpl.handleException(Unknown Source)
at sun.security.ssl.SSLSocketImpl.handleException(Unknown Source)
... 18 more
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.security.ssl.InputRecord.readFully(Unknown Source)
at sun.security.ssl.InputRecord.read(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readDataRecord(Unknown Source)
... 18 more
*/
Usage:
public static void main(String[] args){
int counter = 1;
for(String url: urls){
new DownloadProcess(url,"\\\\fileshare.server\\xyz"+(counter++)+".txt").execute();
}
}
You are going to have to change your connection timeout serverside. I picked up a few links along the way if they are of any importance:
Modify Session Security settings
Lengthening salesforce session timeout
Hope this helps, good luck and let me know :)
Connection Reset means the remote side is closing the connection with a TCP RST (reset) packet. You need to find out what the remote side isn't liking and fix it.
If the remote side is Apache maybe you are running into the KeepAliveTimeout value. By default that is 5 seconds. It really sounds like you are running into some sort of configured limit on the remote side. When that happens the server is kicking you off with a reset.
I am attempting to connect to an Oracle database through Java with the Oracle JDBC driver with the following code (obscuring the host, service, user, and password):
import java.sql.*;
public class Main {
public Main () {
try {
String host = "HOST_NAME";
String port = "1521";
String service = "SERVICE_NAME";
String user = "SCHEMA_USER";
String password = "SCHEMA_PASSWORD";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=" +
host +
")(PORT=" +
port +
")))(CONNECT_DATA=(SERVICE_NAME=" +
service +
")))",
user,
password);
connection.close ();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main (String args) {
new Main ();
}
}
However, I receive the following error:
java.sql.SQLException: IO Error: The Network Adapter could not establish the connection
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:458)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:546)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:236)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:521)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.acxiom.axle.reporting.database.DatabaseConnection.connect(DatabaseConnection.java:23)
at com.acxiom.axle.reporting.Reporting.establishDatabaseConnection(Reporting.java:53)
at com.acxiom.axle.reporting.Reporting.beginReporting(Reporting.java:20)
at com.acxiom.axle.reporting.Entry.<init>(Entry.java:28)
at com.acxiom.axle.reporting.Entry.main(Entry.java:118)
Caused by: oracle.net.ns.NetException: The Network Adapter could not establish the connection
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:392)
at oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:434)
at oracle.net.ns.NSProtocol.establishConnection(NSProtocol.java:687)
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:247)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1102)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:320)
... 11 more
Caused by: java.net.UnknownHostException: null
at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
at java.net.InetAddress$2.lookupAllHostAddr(Unknown Source)
at java.net.InetAddress.getAddressesFromNameService(Unknown Source)
at java.net.InetAddress.getAllByName0(Unknown Source)
at java.net.InetAddress.getAllByName(Unknown Source)
at java.net.InetAddress.getAllByName(Unknown Source)
at oracle.net.nt.TcpNTAdapter.connect(TcpNTAdapter.java:117)
at oracle.net.nt.ConnOption.connect(ConnOption.java:133)
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:370)
... 16 more
The strange thing is, I can connect to the database from PL/SQL Developer, I can ping the remote host, and I can telnet to the remote host on port 1521.
Why would only Java appear to give an UnknownHostException, but I can connect and ping the host with other applications?
EDIT: I removed "hr/hr" from the connection string above. I have tried the connection as-is with it removed and still receive the same error. I've also tried changing the connection string to match the version morgano listed in his answer, with the same result. Finally, I tried to change the port number to a port I know it's not listening on, and it still receives the same error.
The connection string is of the correct format. The problem is that the host isn't set. It's null, or perhaps the string "null". There's simply no other way to generate the error message java.net.UnknownHostException: null
In your sample code, you write String host = "HOST_NAME";. This makes it look like in your real code you are assigning a constant string to the variable host. However, I'm going to stick my neck out and say that in your real code you are not doing this. You are looking up the host name from somewhere, this lookup fails for some reason, you don't check this, and hence you pass a null value into the connection string.
Your JDBC url is wrong, according to the documentation it should be something like:
jdbc:oracle:driver_type:[username/password]#//host_name:port_number/service_name
In your case your code would be something like:
import java.sql.*;
public class Main {
public Main () {
try {
String host = "HOST_NAME";
String port = "1521";
String service = "SERVICE_NAME";
String user = "SCHEMA_USER";
String password = "SCHEMA_PASSWORD";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = DriverManager.getConnection(
"jdbc:oracle:thin:#//" + host
+ ":" + port + "/" + service, user, password);
connection.close ();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main (String args) {
new Main ();
}
}
I have a problem with sending emails in Java. I am using the JavaMail api to send emails. I have a program which downloads an email attachment using pop3, reads the content, does some manipulation and then sends the result in an email using smtp.
The program works fine until the last step where it sends the email and I get the following exception.
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at com.adidas.monitoring.SendMail.sendMail(SendMail.java:46)
at com.adidas.monitoring.MainClass.main(MainClass.java:115)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(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 com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:321)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:237)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
I am using the following code to send the email
public void sendMail(String strMailContent)
{
MimeMessage emailMessage;
Properties emailProperties = new Properties();
try {
emailProperties.load(new FileInputStream("Email.ini"));
} catch (IOException e){
DataLogger.logger.error(e.getMessage());
}
/*Get the properties from the email configuration file*/
String From = emailProperties.getProperty("Email.From");
String ToAdd = emailProperties.getProperty("Email.To");
String CC = emailProperties.getProperty("Email.CC");
String Subject = emailProperties.getProperty("Email.Subject");
String Host = emailProperties.getProperty("Email.Gateway");
emailProperties.setProperty("mail.smtp.host", Host);
Session emailSendSession = Session.getDefaultInstance(emailProperties);
try{
emailMessage = new MimeMessage(emailSendSession);
emailMessage.setFrom(new InternetAddress(From));
emailMessage.addRecipients(javax.mail.Message.RecipientType.TO,ToAdd);
emailMessage.addRecipients(javax.mail.Message.RecipientType.CC,CC);
emailMessage.setSubject(Subject);
emailMessage.setText(strMailContent);
Transport.send(emailMessage);
}
catch (Exception mailEx)
{
mailEx.printStackTrace();
}
}
The above code works fine when I use it with other programs. But when I am using it along with the pop3 code in this case, I have this error. Strange thing is the host is shown as localhost even though I set the property "mail.smtp.host".
Any help on this topic is really appreciated.
I want the request of http get request using the following java code.
But, uncertainly i am getting the following exception.
import java.net.*;
import java.io.*;
public class API {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
The Error or exception is as follows:
Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:337)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:198)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:180)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:388)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:483)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:213)
at sun.net.www.http.HttpClient.New(HttpClient.java:300)
at sun.net.www.http.HttpClient.New(HttpClient.java:316)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:992)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:928)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:846)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1296)
at API.main(API.java:8)
I'm guessing you have a firewall and it's blocking this HTTP get request.
You code should work as you expect it. Something outside the Java runtime is preventing the connection.
Check whether you can ping to http://www.oracle.com/.
If you can ping check whether you are behind a proxy server.
If so provide -Dhttp.proxyHost and -Dhttp.proxyPort while starting the JVM
java -Dhttp.proxyHost=<Your Proxy Server Name/IP> -Dhttp.proxyPort=<Your Proxy Server Port>
I am trying to fetch and download file in html format. Following is the code block:
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
System.setProperty("http.proxyHost", "webcache.mydomain.com");
System.setProperty("http.proxyPort", "8080");
URL url = new URL("http://www.java2s.com/");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
Here, when i am trying to Run this java file it show me following error:
D:\Build>javac URLReader.java
D:\Build>java URLReader
Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:388)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:523)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:227)
at sun.net.www.http.HttpClient.New(HttpClient.java:300)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:977)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:925)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:836)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1172)
at java.net.URL.openStream(URL.java:1010)
at URLReader.main(URLReader.java:12)
I don't think there any problem with code because When i tried to run this code at Home it worked for me. But when i tried it in my office it showed me the error!
So i guess there must be some kind of blockage in my office.
Can i set any proxy here in code so that it might work?
If you are behind a proxy you need to configure Java to use it. Read here on how to set your proxy for your network program
Try this as mentioned in this link http://docs.oracle.com/javase/6/docs/technotes/guides/net/proxies.html
//Set the http proxy to webcache.mydomain.com:8080
System.setProperty("http.proxyHost", "webcache.mydomain.com");
System.setPropery("http.proxyPort", "8080");
// Next connection will be through proxy.
URL url = new URL("http://java.sun.com/");
InputStream in = url.openStream();
// Now, let's 'unset' the proxy.
System.setProperty("http.proxyHost", null);
// From now on http connections will be done directly.