Java Networking "Connection Refused: Connect" - java

I have been trying to get a simple networking test program to run with no results.
Server:
import java.io.*;
import java.net.*;
public class ServerTest {
public static void main(String[] args) {
final int PORT_NUMBER = 44827;
while(true) {
try {
//Listen on port
ServerSocket serverSock = new ServerSocket(PORT_NUMBER);
System.out.println("Listening...");
//Get connection
Socket clientSock = serverSock.accept();
System.out.println("Connected client");
//Get input
BufferedReader br = new BufferedReader(new InputStreamReader(clientSock.getInputStream()));
System.out.println(br.readLine());
br.close();
serverSock.close();
clientSock.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
Client:
import java.io.*;
import java.net.*;
public class ClientTest {
public static void main(String[] args) throws IOException {
final int PORT_NUMBER = 44827;
final String HOSTNAME = "xx.xx.xx.xx";
//Attempt to connect
try {
Socket sock = new Socket(HOSTNAME, PORT_NUMBER);
PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
//Output
out.println("Test");
out.flush();
out.close();
sock.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
The program works just fine when I use 127.0.0.1 or my internal IP for the hostname. But whenever I switch to my external IP address, it throws a java.net.ConnectException: Connection refused: connect error.
I purposely picked such an uncommon port to see if that was the problem, with no luck.
I can connect with no problems using telnet, but when I try to access the port with canyouseeme.org, it tells me the connection timed out.
I even tried to disable all firewalls and antivirus including the Windows default ones and the router firewall, with all ports forwarded and DMZ enabled, and it still says that the connection timed out. I use Comcast as my ISP, and I doubt that they block such a random port.
When I use a packet tracer, it shows TCP traffic with my computer sending SYN and receiving RST/ACK, so it looks like a standard blocked port, and no other suspicious packet traffic was going on.
I have no idea what is going on at this point; I have pretty much tried every trick I know. If anyone know why the port might be blocked, or at least some way to make the program work, it would be very helpful.

These problem comes under the following situations:
Client and Server, either or both of them are not in network.
Server is not running.
Server is running but not listening on port, client is trying to connect.
Firewall is not permitted for host-port combination.
Host Port combination is incorrect.
Incorrect protocol in Connecting String.
How to solve the problem:
First you ping destination server. If that is pinging properly,
then the client and server are both in network.
Try connected to server host and port using telnet. If you are
able to connect with it, then you're making some mistakes in the client code.

For what it's worth, your code works fine on my system.
I hate to say it, but it sounds like a firewall issue (which I know you've already triple-checked) or a Comcast issue, which is more possible than you might think. I'd test your ISP.

Likely the server socket is only being bound to the localhost address. You can bind it to a specific IP address using the 3-argument form of the constructor.

I assume you are using a Router to connect to Internet. You should do Port Forwarding to let public access your internal network. Have a look at How do you get Java sockets working with public IPs?
I have also written a blog post about Port forwarding, you might wanna have a look :) http://happycoders.wordpress.com/2010/10/03/how-to-setup-a-web-server-by-yourself/
But I still couldn't get this accessed over public IP, working on it now...

I had the same problem because sometimes the client started before server and, when he tried to set up the connection, it couldn't find a running server.
My first (not so elegant) solution was to stop the client for a while using the sleep method:
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
I use this code just before the client connection, in your example, just before Socket sock = new Socket(HOSTNAME, PORT_NUMBER);
My second solution was based on this answer. Basically I created a method in the client class, this method tries to connect to the server and, if the connection fails, it waits two seconds before retry.
This is my method:
private Socket createClientSocket(String clientName, int port){
boolean scanning = true;
Socket socket = null;
int numberOfTry = 0;
while (scanning && numberOfTry < 10){
numberOfTry++;
try {
socket = new Socket(clientName, port);
scanning = false;
} catch (IOException e) {
try {
Thread.sleep(2000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
return socket;
}
As you can see this method tries to create a socket for ten times, then returns a null value for socket, so be carefull and check the result.
Your code should become:
Socket sock = createClientSocket(HOSTNAME, PORT_NUMBER);
if(null == sock){ //log error... }
This solution helped me, I hope it helps you as well. ;-)

Related

Java : Opening client socket

I work on a java application.
I got a java socket server mapped with a #ServerEndpoint("/wsock")
Form my javascript code I access the WebSocket from this URL :
ws://192.9.200.73:8084/socketserver/wsock
I want now access to this socket from my java code. But how can I specify the address "socketserver/wsock" ? I've tried something but I got every time an error message.
This is my test :
Socket s = new Socket("localhost/socketserver/wsock", 8084);
But it doesn't work, I got everytime an error message: ".UnknownHostException: localhost/socketserver/wsock"
Any idea?
Thank's
public static boolean pingHost(String host, int port, int timeout) {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(host, port), timeout);
return true;
} catch (IOException e) {
return false; // Either timeout or unreachable or failed DNS lookup.
}
}
Try this. Its something like ping. If you get true its connected. But your server should be ready.
You use a Websocket client. You can't use a Socket directly for this. There is a superimposed protocol.

How to figure out to which server a client connected to

I'm using Netty to build a client-server network communication. Is it possible to find out to which app a client has connected to in case of success?
It's the following problem I try to solve: If a Tomcat Server is listening to port 8080 my client app successfully connects to the "server". Looks like it doesn't matter who is listening to the port.
How can I find out if my server app is currently started and listening to the port instead of e.g. Tomcat?
This is the connection code of the client:
public void run(){
//disconnectTest();
createBootstrap( new Bootstrap(), new NioEventLoopGroup(), true);
}
public void createBootstrap( Bootstrap b, EventLoopGroup eventLoop, boolean initialAttempt){
mWorkerGroup = eventLoop;
try {
b.group(mWorkerGroup)
.channel(NioSocketChannel.class)
.option(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
.handler(new ClientChannelInitializer());
logger.info("Connecting client...");
b.connect(mHost, mPort)
.addListener( new ConnectionListener(this, initialAttempt));
} catch (Exception e) {
logger.error("Failed to connect client to server '" +mHost +": " +mPort +". Error: ", e);
}
}
Snippet from the ConnectionListener:
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
System.out.println("success");
}else{
System.out.println("error");
}
}
EDIT:
If you want check the availability of the server withing the client App, you can use certain tools that Java7 can give us, for example, using this code:
private static boolean available(int port) {
try (Socket ignored = new Socket("localhost", port)) {
return false;
} catch (IOException ignored) {
return true;
}
}
This does not have to be a specific function Netty. More info here:
Sockets: Discover port availability using Java
Enjoy.
To check it outside you client app:
To test the server status I use the Hercules software client.If you know that server will respond someting, using hercules you can send a dummy data y wait the server response.
How you can see, Hercules, allows too makes a ping to the server :)
Hope it helps.

Client-Server communication between Raspberry Pi and Android

I am trying to setup a client-server system with the Pi acting as the server, and the Android device being the client. Every time I run the code (I cobbled together from the internet) the client throws an IOException:
Connection timed out: connect
I just discovered that when I try to ping the Pi's IP it is unreachable.
How can I fix this?
Note I am currently testing Java code on a Windows PC until I get it working.
Client Code (Java):
import java.io.*;
import java.net.*;
public class client
{
static Socket clientSocket;
static String homeIp="192.168.0.105"; //internal ip of server (aka Pi in this case)
static int port=4242;
public static void main(String [] args)
{
sendToPi("I sent a message");
}
public static void sendToPi(String s)
{
//wordsList.append("in sendToPi()\n");
System.out.println("in sendToPi()");
//Log.e("aaa","in sendToPi()\n");
try {
clientSocket = new Socket(homeIp, port);
PrintStream out = new PrintStream(clientSocket.getOutputStream());
out.println(s);
} catch (UnknownHostException e) {
//Log.e("aaa","Don't know about host: "+homeIp+"."+e.getMessage());
System.out.println("Don't know about host: "+homeIp+"."+e.getMessage());
//System.exit(1);
} catch (IOException e) {
//Log.e("aaa","Couldn't get I/O for the connection to: "+homeIp+"."+e.getMessage());
System.out.println("Couldn't get I/O for the connection to: "+homeIp+"."+e.getMessage());
//System.exit(1);
}
}
}
Server Code (C): I used code from here exactly as written. compiled as server. Started with ./server 4242
In my case the solution was to explicitly forward the client port in my router.

Android and Java Socket don't have the same behavior

I'm using Java to implement some socket programs.
I found that both of Android and Java have java.net.Socket, but the source code are not the same, so that they have different behavior.
I have a server(maybe PC or Android), and the server has multiple network interface(E.g. Ethernet, Wireless, USB or Bluetooth). The client will try to connect all the server network interface at the same time(one connection one thread). Until the client finds an available connection, they will communicate via the connection. In this way, I expect that the connection speed will not too low.
But when the client is trying to connect to server, it may encounter a repeat-connect situation in Android device(Android SDK). If the program encounter the repeat-connect situation, the previous connection will be reset or be replaced(I'm not sure) by the latter connection. At the same time, when reading or writing the previous connection, it will throw java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer). In the other hand, when reading or writing the latter connection, it is normal, but the connection speed is not very fast.
This problem seems to not be happened on PC but happened on Android when the client is trying to connect to server.
How can I solve it?
EDIT
The client code as below:
private Socket socket;
private IP ip;
private IP[] IPs;
private boolean closing;
private int socketTriedCount;
...
socketTriedCount = 0;
for (final IP ipObj : IPs) {
if (closing) {
break;
}
new Thread() {
#Override
public void run() {
try {
if (socket == null) {
final Socket s = new Socket();
s.connect(new InetSocketAddress(InetAddress.getByName(ipObj.getIP()), ipObj.getPort()), timeout);
synchronized (Client.this) {
if (socket != null) {
//Should not be happened
//s.close();
socketTriedCount++;
} else {
ip = ipObj;
socket = s;
socketTriedCount++;
}
}
}
} catch (final Exception ioE) {
socketTriedCount++;
}
}
}.start();
}

Server not receiving message from client with correct IP and port opened

What can cause this to happen?
I moved my laptop to a friends house to work on this project. I opened the same port on his xfinity router, and changed all areas of my code to his IP. However it appears that the client is sending a message and the server has never getting past this part of code
System.out.println("running server!");
int nreq = 1;
try{
//SET ME PORT
ServerSocket sock = new ServerSocket(7332);
for(;;){
Socket newsock = sock.accept();
System.out.println("Creating thread...");
//Broken Old Login crap, needs reworked for map n stuff anyhow now
// Thread t = new ThreadHandler(newsock, nreq);
Thread t = new RequestInterpreter(newsock, nreq);
//t.run();
t.start();
nreq++;
}
}
catch(Exception e)
{
e.printStackTrace();
}
It never gets to print "Creating thread". I'm not sure where to begin with what could be going wrong here?
The only thing that has changed is the house, IP, router, and internet. Works everywhere else. What about those changing could block the client from sending a
Here is a test client I wrote also.
import java.io.DataInputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class testClientConnection {
public static void main(String[] args) {
System.out.println("Starting testConnection");
try{
Socket s = new Socket("xx.xx.xx.xxx", 7332);
DataInputStream fromServer = new DataInputStream(s.getInputStream());
PrintWriter toServer = new PrintWriter(s.getOutputStream(), true);
toServer.println("account name");
toServer.println("password");
toServer.println("Login");
System.out.println("Sent message...");
String response = fromServer.readLine().toString();
//Toast the result here? //testing
System.out.println("response: " + response);
if (response.equals("Login Success")) {
System.out.println("Login Success!!!");
}
}
catch(Exception e){ /
}
}
}
HUGE UPDATE!
Ok so my client was an android phone and I turned the wifi off, so it fell onto 4g-LTE. Then it worked. So... Something is blocking the client side code. What might that be?
The firewall on your friend's router is the usual suspect.
Second suspect is the firewall on the target machine.
Try disabling those.
The problem will be NAT on the router.
Servers don't work behind NAT devices unless you set up port-forwarding so that the router knows where to send an incoming request from outside.

Categories

Resources