How to figure out to which server a client connected to - java

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.

Related

Cannot access port of Jetty Server

I have the problem that I get a 504 if I try to access the Jetty Server on my private server. The exact message is "ReadResponse() failed: The server did not return a complete response for this request. Server returned 0 bytes.".
I create the server with
ContextHandler context = new ContextHandler("/");
SessionHandler sessions = new SessionHandler(new HashSessionManager());
sessions.setHandler(new WebHandler(this));
context.setHandler(sessions);
// Setup the server
final Server server = new Server(getConfig().getInt("server.port"));
server.setSessionIdManager(new HashSessionIdManager());
server.setHandler(sessions);
server.setStopAtShutdown(true);
// Start listening
getProxy().getScheduler().runAsync(this, new Runnable() {
#Override
public void run() {
try {
server.start();
getLogger().warning("Webserver started on URI: " + server.getURI() + ", state: " + server.getState());
} catch (Exception e) {
getLogger().warning("Unable to bind web server to port.");
e.printStackTrace();
}
}
});
If I start the server on localhost all things work well, but if I put it on my private Hetzner server (Debian 10) I get the error I've written above. The firewall is set to accept all ports. If I create a tunnel to my server via ssh the site loads infinitely long without showing a result.
I hope you can help me :)
Edit: I saw that he tried to connect via IPv6. I forced it to use IPv4, but same result. Here's the netstat output:
tcp6 0 0 :::8092 :::* LISTEN 4581/java

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.

Android App can't connect with Java Server via Socket

I m trying to create a simple test application that connect via Socket to my computer (in localhost).But it thows some exception and I can't figure out how to solve it. NOTE: I m running the apk in my phone (not in an emulator)
Java Server Code
public class Main {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Thread t = new Thread(){
#Override
public void run(){
System.out.println("Server is running and listening ... ");
try{
ServerSocket ss = new ServerSocket(7000);
while(true){
Socket s = ss.accept();
System.out.println("Connesso");
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println("Received from Client: "+ dis.readUTF());
dis.close();
s.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
};
t.start();
}
}
And this is the
Andorid Client Code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button sendBTN;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendBTN=(Button)findViewById(R.id.button);
sendBTN.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Thread t = new Thread(){
#Override
public void run(){
try {
System.out.println("Starting Connection");
Socket s = new Socket("127.0.0.1", 7000);
System.out.println("Connection DONE");
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF("Let's Test The Socket");
dos.flush();
dos.close();
s.close();
System.out.println("Closing socket");
} catch (UnknownHostException e){
System.out.println("There was an Unknown Erorr:");
e.printStackTrace();
} catch (IOException e) {
System.out.println("There was an IOException:");
e.printStackTrace();
}
}
};
t.start();
Toast.makeText(this, "Messagge Sent...", Toast.LENGTH_SHORT).show();
}
}
What I get it this error:
I also tried some other ports like 1432 or 8000 or 8080 but the result is the same
Then I tried to change the IP from 127.0.0.1 to my own PC ip.. and what I get is this error..
EDIT:
I tried to run the app inside an Emulator using 10.0.2.2 as IP and everything woks fine.. I also tried to use my Private Ip in another JAVA Client program and it works fine.. So the problem is just the connection beetween my real phone and my PC (even if they are in the same network)
Make sure the IP when set to use your local machine from the emulator is 10.0.2.2
When you are using your phone and your PC:
If you are on the same network, make sure you're using the appropriate IP for your PC on your network as the server connection host. I usually set my physical machines to static IPs on my network (through my router) so I don't have to constantly look at what they are, but this is by no means a requirement.
If you are using your phone off of your home network, you will have to use the IP your ISP gives to connect, and make sure that the port is forwarded appropriately in your router if you have one set up.
In either case, you'll need to make sure the firewall is allowing incoming connections on the port you are specifying.
Ok I found the solution.
Then I deleted the exception I ve made in my firewall for port 7000 and I created a new exception which allow the connection using port 3000 and now it works fine.
If you're trying to connect the localhost listening server via Android Virtual Device, you must first check whether the "mobile data" in the AVD is in "On" state, since it doesn't work if it is in "Off" state, well I don't know the exact reason but it works like that.

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.

Java Networking "Connection Refused: Connect"

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. ;-)

Categories

Resources