I was learning socket programming in Java and had written a simple program for connecting a client server to a socket server on a local host. But every time when I run the ClientServer program it gives an error stating connection :refused.
I am enclosing both the client code and server code that i wrote and also enclosing the console output.
package Classes;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class ClientSer {
/**
* #param args
* #throws IOException
* #throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
// TODO Auto-generated method stub
Socket s = new Socket("localhost",1029);
OutputStreamWriter os = new OutputStreamWriter(s.getOutputStream());
String str = "tEST mESSAGE";
os.write(str);
os.flush();
}
}
This is the server code:
package Classes;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketSer {
public static void main(String args[]) throws Exception{
ServerSocket ss = new ServerSocket(1029);
Socket s = ss.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str = br.readLine();
System.out.print(str);
}
}
Console output:
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.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at Classes.ClientSer.main(ClientSer.java:18)
In the server, do you know what interface it's listening on?
I would start the server and then use telnet to try to connect rather than your client. You might find the server is NOT listening on localhost. Or maybe it's listening on every interface (127.0.0.1 plus your local network). I just don't know if I trust SocketServer(portNumber).
I would consider creating an unbound SocketServer and then use socket.bind(), feeding it an InetSocketAddress object constructed with both host and port.
Related
Grrr, I feel that this should be so obvious yet I can't find the solution.
For testing purposes I have created a simple Client and Server for an RMI application. I can successfully run the client and server over a local network. I can also successfully run the application when connected through a Windows 10 Built-In VPN connection. However, when connected via an OpenVPN connection I receive a Connection refused to host exception when calling a method (String response = lookup.helloTo(txt); in the Client code) on the remote object returned from the successful call to lookup = (RMIInterface)Naming.lookup("//192.168.10.14/MyServer");.
All my Google searches state that the java.rmi.server.hostname property must be set which I have done in this case. I am thinking that the issue may be between the VPN client IP address (10.8.0.14) and the server IP address (192.168.10.14). I can ping the server IP address and telnet to port 1099 on the server successfully.
Here is my code. I was hoping if someone could see something that I am missing or doing wrong or if I am on the right track regarding the VPN Client IP <=> Server IP.
Remote Interface:
package devel;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface RMIInterface extends Remote {
public String helloTo(String name) throws RemoteException;
}
Server:
package devel;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class ServerOperation extends UnicastRemoteObject implements RMIInterface {
private static final long serialVersionUID = 1L;
protected ServerOperation() throws RemoteException {
super();
}
#Override
public String helloTo(String name) throws RemoteException {
System.err.println(name + " is trying to contact!");
return "Server says hello to " + name;
}
public static void main(String[] args) {
try {
java.lang.System.setProperty("java.rmi.server.hostname", "192.168.10.14");
java.rmi.registry.LocateRegistry.createRegistry(1099);
Naming.rebind("//192.168.10.14/MyServer", new ServerOperation());
System.err.println("Server is ready");
} catch(Exception exc) {
System.err.println("Server exception: " + exc.toString());
exc.printStackTrace();
}
}
}
Client:
package devel;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import javax.swing.JOptionPane;
public class ClientOperation {
private static RMIInterface lookup;
public static void main(String[] args) throws MalformedURLException, RemoteException, NotBoundException {
lookup = (RMIInterface)Naming.lookup("//192.168.10.14/MyServer");
String txt = JOptionPane.showInputDialog("What is your name?");
String response = lookup.helloTo(txt);
JOptionPane.showMessageDialog(null, response);
}
}
Exception received:
Exception in thread "main" java.rmi.ConnectException: Connection refused to host: 192.168.10.14; nested exception is:
java.net.ConnectException: Connection timed out: connect
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(Unknown Source)
at sun.rmi.transport.tcp.TCPChannel.createConnection(Unknown Source)
at sun.rmi.transport.tcp.TCPChannel.newConnection(Unknown Source)
at sun.rmi.server.UnicastRef.invoke(Unknown Source)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(Unknown Source)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(Unknown Source)
at com.sun.proxy.$Proxy0.helloTo(Unknown Source)
at devel.ClientOperation.main(ClientOperation.java:17)
Caused by: java.net.ConnectException: Connection timed out: 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.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(Unknown Source)
at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(Unknown Source)
... 8 more
I have been trying to connect Bitly REST API using Java. I want to use shorten method from Bitly API. Here is my code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.BasicConfigurator;
public class PostRequestClient {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
BasicConfigurator.configure();
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
"https://api-ssl.bitly.com/v3/shorten");
StringEntity input = new StringEntity("{\"access_token\":<my_access_token>,\"longUrl\":\"https://docs.appian.com/suite/help/18.1/Custom_Function_Plug-ins.html\"}");
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
if (response.getStatusLine().getStatusCode() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
httpClient.getConnectionManager().shutdown();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have referenced this code from https://www.mkyong.com/webservices/jax-rs/restful-java-client-with-apache-httpclient/. Please let me know your thoughts whether I am calling the bitly api correctly or not.
I am getting following error:
0 [main] DEBUG org.apache.http.impl.conn.SingleClientConnManager - Get connection for route HttpRoute[{s}->https://api-ssl.bitly.com]
31 [main] DEBUG org.apache.http.impl.conn.DefaultClientConnectionOperator - Connecting to api-ssl.bitly.com/XX.XXX.XXX.21:443
21059 [main] DEBUG org.apache.http.impl.conn.DefaultClientConnectionOperator - Connect to api-ssl.bitly.com/XX.XXX.XXX.21:443 timed out. Connection will be retried using another IP address
21059 [main] DEBUG org.apache.http.impl.conn.DefaultClientConnectionOperator - Connecting to api-ssl.bitly.com/XX.XXX.XXX.20:443
42080 [main] DEBUG org.apache.http.impl.conn.DefaultClientConnection - Connection closed
org.apache.http.conn.HttpHostConnectException: Connection to https://api-ssl.bitly.com refused
42080 [main] DEBUG org.apache.http.impl.conn.DefaultClientConnection - Connection shut down
42080 [main] DEBUG org.apache.http.impl.conn.SingleClientConnManager - Releasing connection org.apache.http.impl.conn.SingleClientConnManager$ConnAdapter#7225790e
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:158)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:149)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:121)
at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:562)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:415)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:820)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:754)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:732)
at com.persistent.plugins.urlshortener.PostRequestClient.main(PostRequestClient.java:70)
Caused by: java.net.ConnectException: Connection timed out: 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 org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:374)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:148)
... 8 more
I would appreciate if you could give me some inputs to fix this error.
Thank you!
The code below has a few issues. First, it's giving me a SocketTimeoutException. This was working just fine a few days ago, but now it's throwing this error. I'm not sure how to trace the problem to the source. I tried increasing the timeout (which I really don't think will work in the end), but it always times out after 18 seconds. What's more strange is that the URL works when I try getting a JSON file from something else (such as http://mysafeinfo.com/api/data?list=englishmonarchs&format=json). I've waited about a day and the issue is still there. Is there anything I could do to resolve this issue?
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Timer;
import java.util.TimerTask;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class SocketTimeoutError {
public static void main(String args[]) {
URL myURL;
TimerTask task = null;
try {
myURL = new URL(
"https://maps.googleapis.com/maps/api/geocode/json?address=Chicago+Illinois");
URLConnection conn = myURL.openConnection();
conn.connect();
conn.setConnectTimeout(4 * 600000);
conn.setReadTimeout(4 * 600000);
//
Timer timer = new Timer();
task = new TimerTask() {
int time = 0;
public void run() {
System.out.println(time++);
}
};
//
System.out.println("Connecting..." + "Timeout="
+ conn.getConnectTimeout());
timer.scheduleAtFixedRate(task, 0, 1000);
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
task.cancel();
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(in);
String status = (String) jsonObject.get("status");
System.out.println(status);
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
}
Here's my console output:
Connecting...Timeout=2400000
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.socketRead(Unknown Source)
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)
at sun.security.ssl.AppInputStream.read(Unknown Source)
at java.io.BufferedInputStream.fill(Unknown Source)
at java.io.BufferedInputStream.read1(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source)
at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at SocketTimeoutError.main(SocketTimeoutError.java:38)
---Edit---
I've been doing this on my work machine. I just tried this code on my home computer and it works just fine. Also, the company I work for has a Google for Work license. I don't understand how it could be a network issue, though, between the company and the google servers, because I'm able to view the json in my Chrome browser.
I've figured out what the issue was. I had to connect through a proxy (which our browsers automatically do and explains why I got a response when I used a web browser). I just had to modify my code in the following way:
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.url.com", 80));
URLConnection myURLConnection = myURL.openConnection(proxy);
I am quite a newbie to Java. Please excuse me if you find this as a very basic question.There are many answers available already in stack overflow about this and I went through almost all the possible helps i can get in Stack overflow and also in some other forums. Unfortunately none of them helped me.
I have client/server program in which the client send a string to server and server just attaches another string to the string sent by client and sends it back to the client.
Server program looks like this.
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class server {
public static void main(String[] args) {
try
{
ServerSocket server = new ServerSocket(7300);
Socket s = server.accept();
DataInputStream inp = new DataInputStream(s.getInputStream());
DataOutputStream out = new DataOutputStream(s.getOutputStream());
String str =inp.readUTF();
str = str+" buddy!";
out.writeUTF(str);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Client looks like This.
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.*;
public class client {
public static void main(String[] args) {
try
{
Socket s = new Socket("192.168.1.3",7300);
DataInputStream inp = new DataInputStream(s.getInputStream());
DataOutputStream out = new DataOutputStream(s.getOutputStream());
out.writeUTF("hi");
System.out.println(inp.readUTF());
Thread.sleep(2000);
out.writeUTF("hello");
System.out.println(inp.readUTF());
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Everything works fine while client writes "hi" and when client starts sending "hello" i am getting Connection reset error. I am not getting what mistake am i doing please help me in resolving this.
The output with the error i am getting looks like this.
hi buddy!
java.net.SocketException: Connection reset by peer: 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 java.io.DataOutputStream.write(Unknown Source)
at java.io.DataOutputStream.writeUTF(Unknown Source)
at java.io.DataOutputStream.writeUTF(Unknown Source)
at sokry.client.main(client.java:18)
In your server example, readUTF is only called once on the DataInputStream, even though the client wrote to the DataOutputStream twice. Thus, simply adding
str = inp.readUTF();
str = str + " buddy!";
out.writeUTF(str);
to your server example, after the last out.writeUTF(str), will solve your problem.
do comment on following line of your client.java file and try.it will work
Thread.sleep(2000);
`//out.writeUTF("hello");;
//System.out.println(inp.readUTF());
because when you are sending "hi" from client to server and server gives reply then it finished it work and it stop connection but in client.java you sending another request to server but server is at rest.
you should start server until client finish it work..
hope it will wait
I am working on messaging over sockets on my local machine. I am trying to message myself, which is emulating me messaging over the internet. Anyhow, I had gotten a bind exception earlier but it seems I may have gotten past that. Now I am getting the :
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.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at class2.main(class2.java:10)
How do I get this connection to work and my messages to pass. Here are the two classes in my program:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class IPMessenger {
public static void main(String[] args) throws IOException{
ServerSocket SC = new ServerSocket(4800);
Socket socket = SC.accept();
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
System.out.println(in.readDouble());
System.out.println("hi");
// out.writeChars("hello");
}
}
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class class2 {
public static void main(String[] args) throws UnknownHostException, IOException{
Socket sock = new Socket("localhost",4800);
DataInputStream in = new DataInputStream(sock.getInputStream());
DataOutputStream out = new DataOutputStream(sock.getOutputStream());
out.writeDouble(5);
//System.out.println(in.readChar());
}
}
java.net.ConnectException: Connection refused: connect
Your server isn't running when you run the client.