Troubleshoot connecting client to server in java - java

I have been having this problem for some time now and although my efforts and my friends help I can't seem to get past this problem .
My problem is I am trying to establish a connection between client and a server using sockets its very common actually, but for some reason client can't seem to connect to the server don't know why , here is my attempts to solve the problem
1- I used http://portforward.com/ to open the used port on my router which is of type "zhone"
2- I changed the port multiple times and every time I used PFPortChecker to see if my port is open
my code is fairly simple it opens server and when client connects to it , the server sends the date and time
my server code looks like this
public class DateServer {
/** Runs the server. */
public static void main(String[] args) throws IOException {
ServerSocket listener = new ServerSocket(6780);
try {
while (true) {
Socket socket = listener.accept();
try {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(new Date().toString());
} finally {
socket.close();
}
}
} finally {
listener.close();
}
}
}
my client code looks like this
public class DateClient {
/** Runs the client as an application. First it displays a dialog box asking for the IP address or hostname of a host running the date server, then connects to it and displays the date that it serves. */
public static void main(String[] args) throws IOException {
//I used my serverAddress is my external ip address
Socket s = new Socket(serverAddress, 6780);
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
JOptionPane.showMessageDialog(null, answer);
System.exit(0);
}
}
even though I continued my attempts
3- I closed my firewall just in case
4- I added connection time out in my server socket
with all my attempts I always get this error
Exception in thread "main" 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 DateClient.main(DateClient.java:13)
note that DateClient.java:13 is this line Socket s = new Socket(serverAddress, 6780);
please help me with this problem , thanks in advance

I tried running your code. First, localhost (127.0.0.1) could solve your problem. On the other side, I changed the ports and IP to my own, and it just works fine (even my external IP). So probably there is something wrong with your port/IP.
In case it works using localhost, your IP was not the right one, or something on your computer is blocking external connections.
Your client code should look like this, for some reason new Socket(String host, int port) wont work.
public class DateClient {
/** Runs the client as an application. First it displays a dialog box asking for the IP address or hostname of a host running the date server, then connects to it and displays the date that it serves. */
public static void main(String[] args) throws IOException {
//I used my serverAddress is my external ip address
InetAddress serverAddress = InetAddress.getByName(String host);
Socket s = new Socket(serverAddress, 6780);
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
JOptionPane.showMessageDialog(null, answer);
System.exit(0);
}
}
If it doesn't work using localhost, your port is not forwarded correctly. Try to log in to your router and forward the port from there.
And indeed, like #Audrius Meškauskas said, you might want to close your PrintWriter on your server, right before closing your ServerSockect listener.

Close the PrintWriter on the server side
Be sure you use localhost (try 127.0.0.1) as the server address. Depending on how are you connecting the Internet, the external Internet address (as shown by various "get my ip" tools on the web) may be different from the actual address to that your network interface is configured and not work from the same machine. More here.

Related

"Connection refused" when connecting to FTP port 990 in Java

I made an array of FTPS clients and tried to connect it to the ip & port of my interest. Here is the code.
public class ftptest
{
public static void delete_files(String path, int n) throws IOException
{
String realpath;
for(int i=0 ; i<n ; i++)
{
realpath = path+i;
File file = new File(realpath);
FileUtils.cleanDirectory(file);
}
}
public static void main(String[] args) throws Exception
{
int number = 1;
String ip = "some_ip";
int port = 990;
FTPSClient[] client = new FTPSClient[number];
System.out.println(ip);
System.out.println("port = "+ port);
for(int i = 0; i < number; i++)
{
String path = "D:\\ftptest\\client"+i;
File file = new File(path);
file.mkdir();
client[i] = new FTPSClient(true);
client[i].setRemoteVerificationEnabled(false);
client[i].setTrustManager
(TrustManagerUtils.getAcceptAllTrustManager());
client[i].enterLocalPassiveMode();
client[i].setControlEncoding("UTF-8");
client[i].connect(ip,port);
System.out.println("Connected to " + ip + ".");
}
}
}
but somehow it fails in the client[i].connect(ip, port) part with the 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 org.apache.commons.net.SocketClient.connect(SocketClient.java:182)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:203)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:296)
at com.samsung.ftptest.ftptest.main(ftptest.java:66)
When it is FTP, not FTPS, it is working fine. Does anybody have any idea why it is not working?
Thank you.
The system on which you're running this, can't connect to port 990 on the server machine. There are a number of reasons this could be the case, including:
The server is not listening on port 990
A firewall is blocking port 990
The first thing you should do is find a client that's successfully connecting to this server using FTPS, and check its configuration:
What port is it configured to use?
Is it using:
explicit FTPS (this is the preferred, standards-compliant way to do FTPS. It connects in plain FTP on port 21, then negotiates up to a secured protocol.
implicit FTPS (this approach has never been a standard, but does occur in the wild. Like HTTPS, a different port (often 990) is used, and an SSL handshakes happens immediately after connection)
Once you know these things, you can put the right port and the right mode into your code.
If you're certain of the port, and that it works from other machines, then a firewall is the likely culprit. Demonstrate that you can't connect, using telnet:
unixprompt$ telnet serverhostname 990
If it hangs, or says "Connection refused", you know that this machine can't reach it. If you get "Connected to ..." you know that at least you have TCP connectivity (then ctrl-] quit to get out).
If you find that it's a firewall, be prepared for a battle. You're struggling with the control connection -- data connections are a whole new fight. Opening firewalls for passive mode explicit FTPS is fairly straightforward, and documented in this IETF draft: https://datatracker.ietf.org/doc/html/draft-fordh-ftp-ssl-firewall-00 -- but firewall admins are notoriously reluctant to do it.
The server probably does not support the (deprecated) implicit FTPS mode.
You better use the explicit mode anyway:
client[i] = new FTPSClient();
// ...
client[i].connect(ip, 21);
(assuming the server does support FTP over TLS/SSL at all)

How to create a ServerSocket Object without the localhost address

Hy guys, my code here to create a simple server works fine with the local host address(127.0.0.1). Here is my code.
import java.io.*;
import java.net.*;
public class Main {
public static void main(String[] args)
{
Zig z = new Zig();
z.start();
}
}
class Zig
{
ServerSocket ss = null;
InetAddress ia = null;
Socket s = null;
private static final int prt = 56540;
Zig()
{
try
{
byte[] addr = {127,0,0,1};
ia = InetAddress.getByAddress(addr);
SocketAddress sa = new InetSocketAddress(ia,prt);
ss = new ServerSocket();
ss.bind(sa);
s = ss.accept();
}
catch (IOException e)
{
e.printStackTrace();
}
}
Zig start()
{
try
{
InputStream i = s.getInputStream();
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String str = null;
while (str != "stp")
{
str = br.readLine();
System.out.println(str);
}
br.close();
isr.close();
i.close();
s.close();
ss.close();
}
catch (IOException e)
{
e.printStackTrace();
}
return this;
}
}
My question is, how can I use the router's IP - 192.168.8.1 instead of 127.0.0.1? I also tried the IP address from http://whatsmyip.org but still got this exception:
java.net.BindException: Cannot assign requested address: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method)
at java.net.DualStackPlainSocketImpl.socketBind(DualStackPlainSocketImpl.java:106)
at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:387)
at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:190)
at java.net.ServerSocket.bind(ServerSocket.java:375)
at java.net.ServerSocket.bind(ServerSocket.java:329)
at Zig.<init>(Main.java:26)
at Main.main(Main.java:8)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Exception in thread "main" java.lang.NullPointerException
at Zig.start(Main.java:38)
at Main.main(Main.java:9)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
I wanted to create a simple server with that i can access remotely with another computer both having internet connection.
Or is there a way I can make communication between two computers over internet?
Regards.
how can I use the router's IP - 192.168.8.1
You cannot use the router's IP. You should use the IP thats available in the system.
Note this error :
> java.net.BindException: Cannot assign requested address: JVM_Bind
The bind is failing because the address isn't that of the system.
If you want your 2 devices to communicate via LAN (local network) you can use the addresses your router assigned to these devices (that's the 192.168.8.X address you mentioned. EDIT: As Prabhu mentioned, use the devices IP Address, not the routers IP-Address! You can usually find the IPs your router assigned to connected devices in your routers admin-interface). Remember that your router might assign a different adress to the same devices in the future. Most routers come with a function that always assigns the same IP to a specific device. Also, some routers block communication between local devices (i.e. between wired and WiFi devives) for security reasons. Check your router's configuration for more information and configuration options!
If you want your devices to connect via internet you have to use your routers global IP-address (thats probably the one you found out using whatsmyip).
Additionally, your router usually just blocks incoming requests from the internet for security reasons. Again, your Router probably has a function called Port forwarding, which allows you to redirect requests to a specific device (and a specific port at that device) in your local network. Use this with care, as this opens (a part) of your routers built-in security mechanisms.
Finally, depending on your provider, you may have a IPv4 address (see Wikipedia) that you share with other customers (So called DS-Lite (Wiki). In this case, you're network is not reachable from the IPv4-internet at all and your only chance is to use the IPv6 Protocol (if available).
Hope that helps.

Java Socket connecting to a public ip-address

I need to make a server and client that connects to the server.
Problem: "the server works. the client can only connect to localhost, it cannot connect to a server on the internet. I want the client to connect to the server, via a public ip-address that the server is hosted on."
First of all, I have made sure that the port is forwarded and reachable i have tested the port, secondly i have disabled firewall completely from the server machine.
below is the test code i am using:
The Server: nothing fancy just simple - terminates if a client is connected, else just awaits a connection.
public class Server {
public static void main(String args[]) {
try {
ServerSocket srvr = new ServerSocket(52000);
srvr.accept();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
The Client: I have used no-ip.com to mask the ip of the server to "biogenserver2.noip.me".
Using .getCanonicalHostName(); will return the ip.
public class Client {
public static void main(String args[]) {
try {
String ip = Inet4Address.getByName("somets.noip.com").getCanonicalHostName();
InetSocketAddress sa = new InetSocketAddress(ip, 52000);
//Socket skt = new Socket("0.0.0.0", 52000); //local - this works fine.
Socket skt = new Socket();
skt.connect(sa);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
When i run this the server connects fine, but the client returns a "connection timeout" exception
Any help will be appreciated. Thanks.
Answer:
"Just for clarity: You have checked the port is open via public IP as returned by no-ip and the server will quit without exception when you run that little testclient (on a machine that is not the server machine) - is that correct?" – Fildor
TL:DR
Don't run the client and server on the same machine and the same network trying to connect to your server through your public ip then to your own local network will result in a client timeout exception
I was running the client and server on the same machine and also the same network. This caused the client timeout exception. I tried running the Client on a different machine and a different network and i was able to connect successfully.
What version of IP protocol your application uses? On linux, you may figure it out with netstat -tunap | grep 52000 and watching whether first field is tcp or tcp6. If latter, then it is possible that problem with IPv6 connectivity exists and you may want to prefer using IPv4 to IPv6 by specifying -Djava.net.preferIPv4Stack=true to JVM.

How to run a simple socket server that allows incoming connections?

I am trying to build a very simple socket server in JAVA that my Flash application can listen to. I am using this tutorial. Everything seems to be working - the JAVA code is compiled and the server is running.
My question is: how can external applications send messages to this server using just an IP address and a port number? My goal is that flash can listen to socket messages sent by an external application.
The Java code:
import java.io.*;
import java.net.*;
class SimpleServer {
private static SimpleServer server;
ServerSocket socket;
Socket incoming;
BufferedReader readerIn;
PrintStream printOut;
public static void main(String[] args) {
int port = 8080;
try {
port = Integer.parseInt(args[0]);
} catch (ArrayIndexOutOfBoundsException e) {
// Catch exception and keep going.
}
server = new SimpleServer(port);
}
private SimpleServer(int port) {
System.out.println(">> Starting SimpleServer");
try {
socket = new ServerSocket(port);
incoming = socket.accept();
readerIn = new BufferedReader(
new InputStreamReader(
incoming.getInputStream()));
printOut = new PrintStream(incoming.getOutputStream());
printOut.println("Enter EXIT to exit.\r");
out("Enter EXIT to exit.\r");
boolean done = false;
while (!done) {
String str = readerIn.readLine();
if (str == null) {
done = true;
} else {
out("Echo: " + str + "\r");
if(str.trim().equals("EXIT"))
done = true;
}
incoming.close();
}
} catch (Exception e) {
System.out.println(e);
}
}
private void out(String str) {
printOut.println(str);
System.out.println(str);
}
}
Maybe I don't understand correctly your problem description, but if you create the server in Java, it listens to its port and not your Flash application. If you want your Flash application to wait for messages from other applications, it must have a server role and listen to a TCP port the same way as this Java server does.
You can connect to and test the given Java server easily by telnet program (available in all operating systems) by providing a host name or an IP address and a port as parameters:
telnet 127.0.0.1 8080
Any other application can connect in a similar way, using just a hostname/IP address and a port. For example in Java, you can create a client socket:
Socket clientSocket = new Socket("localhost", 8080);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
By not specifying an IP address for your socket, it will listen on 0.0.0.0 (all interfaces).
In fact, that will usually be your computer's IP / the server's IP.
Assuming that your application runs on your computer at home, there are three cases that cover most of the connection situations:
Connecting from the same machine:
Use 127.0.0.1:8080
Connecting from the same LAN (e.g. your brother's PC):
Use your LAN IP (e.g. 192.168.1.4:8080)
Connecting from WAN (outside your routers LAN) (internet e.g.):
Use your WAN IP.(e.g. 84.156.74.194). There are plenty websites, that tell you your WAN IP like this
You may have to setup your router, to forward the port 8080 to your PC
For simple connection tests, one could use a telnet client.
I think you are missing the point of client/server socket applications.
If you are building the socket server (with whatever programming language you chose), you will then need to connect with (a) socket client(s) to this server. After a connection is successfully established (persistent) between the client and the server, you can start what ever kind of communication you have implemented between them.
The server always acts as the passive, the client as active part in a socket server/client constellation.
I was checking the link that you are referring to. In that, the procedure to create a stand-alone server is mentioned which is the code that you have pasted as well.
According to the link, the application acts as the client and uses the XMLSocket methods to connect to this server. This application is the flash application that you are talking about. As mentioned in the link, by using the following code any flash application can connect and talk to the server:
var xmlsock:XMLSocket = new XMLSocket();
xmlsock.connect("127.0.0.1", 8080);
xmlsock.send(xmlFormattedData);
When you mention
My goal is that flash can listen to socket messages sent by an external application.
its actually the flash application that is the client and it cannot listen unless programmed to act as a server. I hope this provides some clarity!

How to kill open server sockets under windows7?

I wrote a simple server client socket program and when I recompile the server I get:
java.net.BindException: Address already in use: 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 java.net.ServerSocket.<init>(Unknown Source)
Therefore my question is how to kill the socket under windows 7? Is there a possible solution to kill it in eclipse?
I appreciate your answer!!
Kill the jvm this fixed the issue when I ran into it. Are you closing the socket in your code before you stop your simple server?
Like RGdev I assume that you still have a javaw process running in the background which keeps the connection open. But it could also be a different server program on your machine which hogs the port you want to use.
You can find out which processes are listening to which port with the netstat command in the cmd shell. The following parameters list (a) all connections including servers, (b) shows the executable which opened the connection and (n) suppresses the substitution of port numbers with service names for well-known ports.
netstat -abn
Here is my code for server side:
import java.io.*;
import java.net.*;
public class ServerSide {
public static void main(String[] args) {
try
{
ServerSocket myServerSocket = new ServerSocket(9999);
System.out.println("Server is waiting on host" + InetAddress.getLocalHost().getCanonicalHostName() + "port= "+ myServerSocket.getLocalPort());
Socket skt = myServerSocket.accept();
BufferedReader myInput = new BufferedReader(new InputStreamReader(skt.getInputStream()));
PrintStream myOutput = new PrintStream(skt.getOutputStream());
String buf = myInput.readLine();
System.out.println("Server readLine");
if(buf!=null)
{
System.out.println("Buf = " + buf);
myOutput.print("Got it?");
}
else
{
System.out.println("Nothing returned in server sidex`x ");
}
skt.close();
System.out.println("Server shutdown");
}
catch(IOException e)
{
e.printStackTrace();
System.out.println("Whooops");
}
}
}
As you can see for clean-up I've written:
skt.close();
But maybe this is not your problem, Maybe your problem is which I had 1 hour ago ;) I used to run a program but the result is not what I expected so I modify it and run it again but the port was busy or already in use! What I do on eclipse? Under the Console where you get the error, on the right side of the window there is red colour rectangle button! It say "Terminate". If you click on that your port will be free. By the way don't forget to check the console for both(Server/Client) sides.
You can also get this error message, when the process already terminated. TCP has a time wait state. This state is used to ensure that no TCP packets from an old connection can be delivered to a new process listening at the same port. Normally you should use the ServerSocket.setRuseAddress(true) to avoid this issue.

Categories