How to use Netty clients within Netty server - java

I'm going to create an authentication server which itself interacts with
a set of different Oauth2.0 servers.
Netty seems to be a good candidate to implement network part here.
But before start I need to clear some details about netty as I'm new to it.
The routine will be as follows:
The server accepts an HTTPS connection from a client.
Then, not closing this first connection, it makes another connection
via HTTPS to a remote Oauth2.0 server and gets data
After all, the server sends the result back to the client which is supposed to keep the connection alive.
How to implement this scenario with Netty?
Do I have to create a new netty client and/or reconnect it each time I need to connect to a remote Oauth2.0 server?
If so, I'll have to create a separate thread for every
outgoing connection which will drastically reduce performance.
Another scenario is to create a sufficient number of Netty clients
within a server at the beginning (when server starts)
and keep them constantly connected to the Oauth2.0 servers via HTTPS.

That's easily done with Netty. First you set up your Netty server using the ServerBootstrap and then in a ChannelHandler that handles your connection from the client you can use e.g. the client Bootstrap to connect to the OAuth server and fetch the data. You don't need to worry about creating threads or similar. You can do it all in a non-blocking fashion. Take a look at and try to understand how this example works:
https://github.com/netty/netty/blob/master/example/src/main/java/io/netty/example/proxy/HexDumpProxyFrontendHandler.java#L44.

Related

REST Server to client communication

I'm developing a Java API for an Adndroid app in Spring. Right now my API is 100% REST and stateless. For the client to receive data, it must send a request first.
However, what I need is the server to send data to the to the client /not the client to the server fisrt/ whenever it is ready with it's task.
I think that some kind of session must be created between the two parties.
My question is: How can I achieve this functionality of the SERVER sending data to the CLIENT when it's ready with it's task? /It is unknown how long the task will take./
What kind of API should I develop for this purpose?
One idiotic workaround is sending a request to the server every n seconds but I'm seeking for a more intelligent approach.
There are multiple options available. You can choose what suits best for you.
Http Long Polling - In this, server holds the request until it's ready with its task (in your case). Here, you don't have to make multiple requests every few seconds (Which is Http Polling).
Server Sent Events - In this, server sends update to the client without long-polling. It is a standardized part of HTML 5 - https://www.w3.org/TR/eventsource/
Websockets - Well, websockets work in duplex mode and in this a persistent TCP connection is established. Once TCP connection is established, both server and client sends data to and fro. Supported by most modern browsers. You can check for Android Websocket Library like autobahn and Java websocket.
SockJs - I would recommend to go with this option instead of plain WebSocket. http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#websocket-fallback-sockjs-enable

Netty4 application as both client and a server

I want to write a program in Netty4 that should act as a server to other clients and also it itself is a client to another server. How to do this in Netty4? So far all examples I have seen are either client or server. Thanks.
There are no special difficulties here. You need to create a part that will act as a server (using ServerBootstrap), and a part that will act as a client (using Bootstrap).
If you need to establish a connection to another server while handling incoming connection from a client, you can place that logic into a ChannelHandler of the server's pipeline.
Netty provides two examples of this approach:
Hex dumping proxy
SOCKS proxy

Implementing a protocol exchanging four messages within a single persistent connection

I have a complete implementation of a protocol where four messages are exchanged between the client (a native Android application) and the server (a standalone Java server) in the following way using a persistent connection through Java sockets:
(client->server): message1
(server->client); message2
(client->server): message3
(server->client): message4
Between sending each message, both client and server have to do heavy mathematical (cryptographic) operations (pairing-based computations over elliptic curves).
This project works properly in my local development machine using sockets and mantaining opened this socket from message1 to the message4 between the Android app and the Java server. Now, I need to do the same with Google AppEngine, but since it does not allow opening sockets, I do not know how can I do it. I already checked the Channel and XMPP APIs, but I do not know whether my use-case applies to that APIs. Is it the right method using Channel and XMPP APIs from AppEngine? Is it possible to emulate the functionality implemented in my local machine through sockets on AppEngine?
Thank you for your response.
Google App Engine doesn't support persistent connections.
You will need to significantly re-design your protocol to run over HTTP.
As an example, message1 can be sent over an HTTP request, message2 can be returned with the matching HTTP response. At that point, your socket connection ends.
You'll have to issue a second HTTP request to open a new socket with message3, and you can return message4 with the second HTTP response.
You can "connect" the first and second HTTP request by using an HTTP session. A session is basically an id with extra data stored on the server side. You'd create the session in the first HTTP request, and pass it as a parameter to the second HTTP request. The server can look up the session id and the associated data when processing the second request.
You can find more info about sessions on SO: How to use session on Google app engine
The XMPP API will not help you, it's for communicating between the GAE server-side code and other XMPP clients that use HTTP as a communcation protocol.
The Channel API can be used to send data from the server->client, but it's actually implemented as an HTTP long poll. Multiple long HTTP requests are used, and you are not guaranteed to have a single socket that stays open; multiple sockets are opened and closed in the process. It will be more complicated that what I described above, and more expensive.

Accept only connections from my application

I am working on a java project where we have a server and a client application. The server accepts a connection and sends requested data to a client through socket programming.
Everything works fine but when uploaded and working on server I get connections from unknown ip's. And this application will be used from many countries so there wont be specific ip's to whitelist.
Is there a way to ban / reject these ip's so that only connections from my application should be accepted by the server using sockets. Is it possible to send custom data when requesting connections to the server so that it will tell the server to accept only these connections.
The selective acceptance you describe falls within the scope of authentication and authorization. You will want connecting clients to:
Identify themselves to you, so you can determine wether they are allowed access to the server. This can be accomplished by many means, ie IP or MAC address whitelisting, client side certificates, basic/digest authentication, or some other custom a uthentication scheme.
Once allowed access, you can further scope down what the connecting client can do in the system via authorization rules.
I recommend taking a look at libraries like Apache Shiro, that will do some of the heavy lifting for you.
After accepting the inbound connection you can use Socket.getInetAddress() on the returned Socket to retrieve and subsequently validate the IP.
If the IP is not allowed, then use Socket.close() to close the unwanted connection.
Edit:
Validation can of course be based on things beyond just IP. Once the connection is open you can use its streams to transfer arbitrary data to identify the client for instance closing the connection following an authentication failure.
Doing this you should, however, consider the possibility of someone being able to intercept your communications. In other words using a secure connection would make sense.
I'm not aware of a way in which you can authenticate clients in Java prior to opening (accepting) the connection.
If your server and client should be validated, you should think about using certificates also.
Here are some more information :
the java class
another SO question

Java Instant Messenger questions

I am looking to build an instant messenger in Java.
Clients will connect to the server to log in.
They will start a conversation with one or more other clients.
They will then post messages to the server that will relay the messages to all the clients.
The client needs to be continually updated when users post messages or log in.
so the way I see it, the client needs to run a server itself in a separate thread so that the main server can send stuff to it. Otherwise the client will have to the poll the main server every xyz seconds to get the latest updates. And that would need a separate thread anayway, as that would be purely for getting updates whereas the 'main' thread would be used for when the client initiates actions such as posting messages/inviting others to conversations etc...
So anyone recommendations on how to write this instant messenger? Does it sound like a good idea to make the connection a 'two-way' connection where both the client and server act as servers? Or is polling a better option? Anyone know how the IRC protocol does this?
There's no real advantage of having 2 connections unless they can be handled independently (for example receiving / sending a file usually done in a separate connection). A connection itself is already a two-way communication channel so it can be used to both send and receive messages, events etc. You don't need to poll server since client is able to maintain persistent connection and just wait for data to appear (optionally sending periodic PING-like message to ensure connection is alive).
IRC uses a single connection to server to exchange text commands. For example one of the main commands:
PRIVMSG <msgtarget> <message>
This command can be originated either by client or by server. Client sends PRIVMSG to notify that it wants to deliver message to one or more destination (in IRC this either user(s) or channel(s)). Server's task here is to properly broadcast this message to appropriate clients.
If you're using raw InputOutput streams then yes this is a good way of doing it. You create one thread on the clientside that acts in a similar fashion as the server thread - waits for any incoming updates and when it does it updates the client. I wouldn't call it a server though. So you'd ideally have 2 TCP/UDP connections one for requests made by the client and one to notify the client of server changes.
This solution in an enterprise environment would probably be done through some kind of messaging framework such as Spring Integration but dig deep enough and it will essentially be a similar way to how you mentioned.
Do you need a fully custom protocol or would it be sufficient to use the XMPP? There are several open source libraries implementing XMPP.
http://xmpp.org/xmpp-software/libraries/
e.g. http://www.igniterealtime.org/projects/smack/
For me, to develop instant messaging service, I will use websocket protocol instead of normal java socket because the normal socket can not work well with HTTP protocol and moreover some network providers and firewalls banned custom ports. If you develop it in normal socket, your service could not be accessed by web clients.
Did you plan to develop the instant messaging service yourself? How about using other protocols such as Jabber?

Categories