Netty 4.0.x Correctly catch a ConnectException - java

I'm developing an application with Netty and I need to handle the ConnectException on the client side thrown in case, for example, of a connect timeout.
Here's the code
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.FutureListener;
public class ConnectTest {
public static void main(String[] args) throws Exception {
Bootstrap b = new Bootstrap();
b.group(new NioEventLoopGroup()).channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
#Override
public void initChannel(SocketChannel ch) throws Exception {
}
});
final ChannelFuture f = b.connect("0.0.0.0", 8080);
f.addListener(new FutureListener<Void>() {
#Override
public void operationComplete(Future<Void> future) throws Exception {
if (!f.isSuccess())
System.out.println("Test Connection failed");
}
});
f.sync();
}
}
And this is the result:
Test Connection failed
Exception in thread "main"
java.net.ConnectException: Connection refused: no further information: /0.0.0.0:8080
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at sun.nio.ch.SocketChannelImpl.finishConnect(Unknown Source)
at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:208)
at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:287)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:524)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:464)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:378)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:350)
at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:116)
at java.lang.Thread.run(Unknown Source)
As you can see the listener works fine, but i still get an ugly stacktrace printed out and I can't figure out where to intercept it.
Any hints?

the culprit is
f.sync()
You could handle ConnectExceptions in the listener :
final ChannelFuture f = b.connect("0.0.0.0", 8080);
f.addListener(new FutureListener<Void>() {
#Override
public void operationComplete(Future<Void> future) throws Exception {
if (!f.isSuccess()) {
System.out.println("Test Connection failed");
handleException(future.cause());
}
}
});
//f.sync();

Related

Getting NotBoundException when Client lookup to server

I am trying to run the rmi tutorial on oracles' website. I am able to run the server, but I receive an error running the client. The error I receive when try to run the client is a NotBoundException exception. How do I fix this error?
Below is the code and exception
Exception
Exception in thread "main" java.rmi.NotBoundException: Server
at java.rmi/sun.rmi.registry.RegistryImpl.lookup(RegistryImpl.java:234)
at java.rmi/sun.rmi.registry.RegistryImpl_Skel.dispatch(RegistryImpl_Skel.java:133)
at java.rmi/sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:468)
at java.rmi/sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:298)
at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:200)
at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:691)
at java.rmi/sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at java.rmi/sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:587)
at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:828)
at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:705)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:704)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
at java.base/java.lang.Thread.run(Thread.java:832)
at java.rmi/sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:303)
at java.rmi/sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:279)
at java.rmi/sun.rmi.server.UnicastRef.invoke(UnicastRef.java:380)
at java.rmi/sun.rmi.registry.RegistryImpl_Stub.lookup(RegistryImpl_Stub.java:123)
at rmi.Client.main(Client.java:13)
I use Server and Client with different project at Port 1212
here is Server
package De_1;
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Server {
public static void main(String[] args) throws RemoteException, AlreadyBoundException {
Registry r = LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
ProductDAO productDAO = new ProductDAOImpl();
r.bind("Server", productDAO);
}
}
and here is Client
package rmi;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Client {
public static void main(String[] args) throws RemoteException, NotBoundException {
Registry r = LocateRegistry.getRegistry(1212);
ProductDAO productDAO = (ProductDAO) r.lookup("Server");
System.out.println("Hay nhap");
Scanner sc = new Scanner(System.in);
while (true) {
String command = sc.nextLine();
StringTokenizer stringTokenizer = new StringTokenizer(command);
String request = stringTokenizer.nextToken();
System.out.println(request);
switch (request) {
case "HELLO": {
productDAO.addProduct();
}
default:
break;
}
}
}
}

problems about error "Exception in thread "main" java.lang.NoSuchMethodError: io.netty.resolver.HostsFileParser.parseSilently()Ljava/util/Map;"

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.ext.web.Router;
public class app extends AbstractVerticle{
#Override
public void start() throws Exception{
Router router = Router.router(vertx);
router.route().handler(routingContext -> {
routingContext.response()
.putHeader("content-type", "text/html")
.end("hello vert.x");
});
vertx.createHttpServer().requestHandler(router::accept).listen(8888);
}
public static void main(String[] args) {
Vertx vertx = Vertx.vertx();
vertx.deployVerticle(new app());
}
}
then error occurs as java.lang.NoSuchMethodError: io.netty.resolver.HostsFileParser.parseSilently()Ljava/util/Map;
Try this way
import io.vertx.core.AbstractVerticle;
import io.vertx.ext.web.Router;
public class Server extends AbstractVerticle {
#Override
public void start() throws Exception {
Router router = Router.router(vertx);
router.route().handler(routingContext -> {
routingContext.response().putHeader("content-type", "text/html").end("hello vert.x");
});
vertx.createHttpServer().requestHandler(router::accept).listen(8080);
}
}
run mvn clean package then java -jar /path/to/jar
Also in java app is not a valid class name.
Class names start with a capital e.g. App

JBREM000200: Remote connection failed: java.io.IOException: An existing connection was forcibly closed by the remote host

This is my client code
package com.tutorialspoint.test;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.tutorialspoint.stateless.testRemote;
public class test
{
BufferedReader brConsoleReader = null;
Properties props;
static InitialContext ctx;
{
props = new Properties();
try {
props.load(new FileInputStream("jndi.properties"));
} catch (IOException ex) {
ex.printStackTrace();
}
try {
ctx = new InitialContext(props);
} catch (NamingException ex) {
ex.printStackTrace();
}
brConsoleReader =
new BufferedReader(new InputStreamReader(System.in));
}
public static void main(String[] args)
{
test _test = new test();
try {
testRemote libraryBean =(testRemote)ctx.lookup("java:global/TestEjb/testBean!
com.tutorialspoint.stateless.testRemote");
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This is deployed on server
package com.tutorialspoint.stateless;
import javax.ejb.Stateless;
#Stateless
public class testBean implements testRemote
{
public void hello()
{
System.out.println("hello");
}
}
package com.tutorialspoint.stateless;
import javax.ejb.Remote;
#Remote
public interface testRemote
{
void hello();
}
I am getting exception on server side:
19:09:12,676 ERROR [org.jboss.remoting.remote.connection] (Remoting "cognam-
pc-26" read-1) JBREM000200: Remote connection failed:
java.io.IOException: An existing connection was forcibly closed by the
remote host
I am getting exception on client side:-
javax.naming.CommunicationException: Could not obtain connection
to any of these urls: localhost:4447 and discovery failed with error:
javax.naming.CommunicationException: Receive timed out [Root exception
is java.net.SocketTimeoutException: Receive timed out] [Root exception
is javax.naming.CommunicationException: Failed to retrieve stub from
server localhost:4447 [Root exception is java.io.StreamCorruptedException:
invalid stream header: 0000000F]]
org.jnp.interfaces.NamingContext.checkRef(NamingContext.java:1414)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:594)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:587)
at javax.naming.InitialContext.lookup(InitialContext.java:392)
at com.tutorialspoint.test.test.main(test.java:37)
It might be that your server is not actually allowing connections to 4447. Check if you can telnet to that port or use netstat -an to query this.
Also ensure that there is no firewall blocking access to the port.
Try shutdown any http traffic capture tools if running (e.g. Fiddler)

SignalR java cannot connect to server

I'm having trouble connecting my java application to my SignalR Server.
The server is very simple and can be found here:
https://code.msdn.microsoft.com/windowsdesktop/Using-SignalR-in-WinForms-f1ec847b
I can connect web clients(javascript) and windows clients (C#) but I'm having trouble with my java client.(https://github.com/SignalR/java-client)
Here is my code so far:
package javaapplication2;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import microsoft.aspnet.signalr.client.SignalRFuture;
import microsoft.aspnet.signalr.client.hubs.HubConnection;
import microsoft.aspnet.signalr.client.hubs.HubProxy;
public class JavaApplication2 {
public static void main(String[] args) throws IOException, InterruptedException, ExecutionException, TimeoutException
{
String ServerURI = "http://localhost:8080/signalr";
HubConnection Connection = new HubConnection(ServerURI);
HubProxy HubProxy = Connection.createHubProxy("MyHub");
HubProxy.on("AddMessage", () -> { System.out.println("Some message"); });
Connection.error(new ErrorCallback() {
#Override
public void onError(Throwable error) {
error.printStackTrace(); //<==SocketException
}
});
SignalRFuture<Void> con =Connection.start();
con.get();
}
}
Update
When I run it I get a "ExecutionException: java.net.SocketException: Connection reset"
Exception in thread "main" java.util.concurrent.ExecutionException: java.net.SocketException: Connection reset
at microsoft.aspnet.signalr.client.SignalRFuture.get(SignalRFuture.java:112)
at microsoft.aspnet.signalr.client.SignalRFuture.get(SignalRFuture.java:102)
at javaapplication2.JavaApplication2.main(JavaApplication2.java:27)
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:209)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:286)
at java.io.BufferedInputStream.read(BufferedInputStream.java:345)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:704)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:647)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:675)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1535)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1440)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
at microsoft.aspnet.signalr.client.http.java.NetworkRunnable.run(NetworkRunnable.java:72)
at java.lang.Thread.run(Thread.java:745)
-If I change "localhost" to something that does not exist ( e.g locahostX) I get a java.net.UnknownHostException
-If If change "localhost" to my IP I don't event get an exception...
-All the other apps work with both (localhost or IP)
At first I thought it was a firewall issue but it wasn't that...
Obviously I'm missing something...
Any ideas?
Thanks
It turns out that I had to use an overload of start,the one that takes as a parameter a ClientTransport object
public SignalRFuture<Void> start(ClientTransport transport)
If anyone has an explanation why the parameterless start method fails ,please post it as an answer and I will mark it as the solution.
Here is a full example that works:
package javaapplication2;
import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import microsoft.aspnet.signalr.client.SignalRFuture;
import microsoft.aspnet.signalr.client.hubs.HubConnection;
import microsoft.aspnet.signalr.client.hubs.HubProxy;
import microsoft.aspnet.signalr.client.transport.ServerSentEventsTransport;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler2;
public class JavaApplication2 {
public static void main(String[] args) throws IOException, InterruptedException, ExecutionException, TimeoutException
{
String ServerURI = "http://localhost:8080/signalr";
HubConnection Connection = new HubConnection(ServerURI);
HubProxy HubProxy = Connection.createHubProxy("MyHub");
HubProxy.on("AddMessage", new SubscriptionHandler2<String, String>() {
#Override
public void run(String e1, String e2) {
System.out.println(e1.toString()+ " -> " +e2.toString());
}
}, String.class, String.class);
SignalRFuture<Void> con =Connection.start(new ServerSentEventsTransport(Connection.getLogger())); //Or LongPollingTransport
con.get();
Scanner inputReader = new Scanner(System.in);
String line = inputReader.nextLine();
while (!"exit".equals(line)) {
HubProxy.invoke("send", "Console", line);
line = inputReader.next();
}
inputReader.close();
Connection.stop();
}
}
If I change "localhost" to something that does not exist ( e.g
locahostX) I get a java.net.UnknownHostException
Are you sure about this?
On the server command prompt run "ipconfig" to get the IP address of the server.
From the client command prompt type "ping " + IP address of the server.
If the ping sends packages, then try to put the IP in the string "ServerURI" to be something like "http://"+ServerIP+":8080/signalr".

Getting NotBoundException while writing a Java RMI chat application :-/

I have written a Java RMI chat application. There are four classes and two interfaces. Here they are:
ChatClient
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Scanner;
com.za.tutorial.rmi.server.ChatServerIF;
public class ChatClient extends UnicastRemoteObject implements ChatClientIF,Runnable {
private ChatServerIF chatServer;
private String name = null;
protected ChatClient(String name, ChatServerIF chatServer) throws RemoteException {
this.name = name;
this.chatServer = chatServer;
chatServer.registerChatClient(this);
}
public void retrieveMessage(String message) throws RemoteException {
// TODO Auto-generated method stub
System.out.println(message);
}
public void run() {
Scanner scanner = new Scanner(System.in);
String message;
while(true){
message = scanner.nextLine();
try {
chatServer.broadcastMessage(name + " : " + message);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
ChatClientDriver
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import com.za.tutorial.rmi.server.ChatServerIF;
public class ChatClientDriver {
public static void main(String[] args) throws MalformedURLException, RemoteException, NotBoundException {
String chatServerURL = "rmi://localhost/RMIChatServer";
ChatServerIF chatServer = (ChatServerIF) Naming.lookup(chatServerURL);
new Thread(new ChatClient(args[0],chatServer)).start();
}
}
ChatClientInterface
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface ChatClientIF extends Remote {
void retrieveMessage(String message) throws RemoteException;
}
ChatServer
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import com.za.tutorial.rmi.client.ChatClientIF;
public class ChatServer extends UnicastRemoteObject implements ChatServerIF {
private ArrayList<ChatClientIF> chatClients;
protected ChatServer() throws RemoteException {
chatClients = new ArrayList<ChatClientIF>();
}
public synchronized void registerChatClient(ChatClientIF chatClient)
throws RemoteException {
this.chatClients.add(chatClient);
}
public synchronized void broadcastMessage(String message) throws RemoteException {
int i = 0;
while(i < chatClients.size()){
chatClients.get(i++).retrieveMessage(message);
}
}
}
ChatServerDriver
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
public class ChatServerDriver {
public static void main(String[] args) throws RemoteException, MalformedURLException {
Naming.rebind("RMIChatServer", new ChatServer());
}
}
ChatServerInterface
import java.rmi.Remote;
import java.rmi.RemoteException;
import com.za.tutorial.rmi.client.ChatClientIF;
public interface ChatServerIF extends Remote {
void registerChatClient(ChatClientIF chatClient) throws RemoteException;
void broadcastMessage(String message) throws RemoteException;
}
When I run it on Commando, first of all I run rmic ChatClient and ChatServer, then rmiregistry. Then i run chatServerDriver which works completely fine. after that, when I run chatClientDriver with a name, I get the following error, I dont understand why :/ Can I get any solution for this?
Thanks :)
Exception in thread "main" java.rmi.NotBoundException: RMIChatServer
at sun.rmi.registry.RegistryImpl.lookup(RegistryImpl.java:136)
at sun.rmi.registry.RegistryImpl_Skel.dispatch(Unknown Source)
at sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:409)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:267)
at sun.rmi.transport.Transport$1.run(Transport.java:177)
at sun.rmi.transport.Transport$1.run(Transport.java:174)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:173)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:553)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:808)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:667)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Unknown Source)
at sun.rmi.transport.StreamRemoteCall.executeCall(Unknown Source)
at sun.rmi.server.UnicastRef.invoke(Unknown Source)
at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
at java.rmi.Naming.lookup(Unknown Source)
at com.za.tutorial.rmi.client.ChatClientDriver.main(ChatClientDriver.java:15)
It also looks like you have a different address in Rebind to what is being used by the client to connect.
Naming.rebind("//localhost/RMIChatServer", new ChatServer());
There's an example implementation on the following Wikipedia page which may be worth comparing against your code.
http://en.wikipedia.org/wiki/Java_remote_method_invocation
Note that using Java 1.5+ you don't need to use rmic anymore see Do we really need to create Stub in java RMI?

Categories

Resources