I am building a Client server app in java ,here is my code
Client
import java.net.*;
import java.io.*;
class ClientCode{
public static void main(String args[]) throws Exception {
int character;
Socket socket = new Socket("112.134.214.53", 8765);
//i have put my public ip instead of 127.0.0.1 in order to test it is working through the internet or not
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
String string = "Hello!\n";
byte buffer[] = string.getBytes();
out.write(buffer);
while ((character = in.read()) != -1){
System.out.print((char) character);
}
socket.close();
}
}
Server
import java.io.*;
import java.net.*;
public class ServerCode{
public static void main(String[] args ){
try{
ServerSocket socket = new ServerSocket(8765);
Socket insocket = socket.accept( );
BufferedReader in = new BufferedReader (new InputStreamReader(insocket.getInputStream()));
PrintWriter out = new PrintWriter(insocket.getOutputStream(), true);
String instring = in.readLine();
out.println("The server got this: " + instring);
insocket.close();
}
catch (Exception e) {}
}
}
both are running on a same machine connected to internet using my home adsl single port router.
Server application run fine but when my client connects to the server through public ip the problem starts ,below is the error message
Exception in thread "main" 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 java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at ClientCode.main(ClientCode.java:6)
My Kaspersky Network monitor is showing me that my port 8765 is ok and working
There may be two possible reasons for this exception to occur:
1- There is no service listening to the port you are attempting to connect to. For debugging you can try loading http://112.134.214.53:8765 using a browser and see if it connects with the server.
2- (If everything else is fine) This could very well be a firewall issue.