High Level Protocols for Bluetooth/WiFi Direct Sockets? - java

When you work with Bluetooth or WiFi Direct in Android, at the end of all of the handshaking and such, you wind up with sockets.
With TCP/IP, we have a zillion-plus-one libraries that layer on top of sockets, for high-level protocols: HTTP, XMPP, IMAP, etc. Courtesy of these libraries, we can deal with more domain-specific abstractions of an operation (e.g., "download this file"), with low-level socket plumbing handled by the library.
Question: Are there equivalents, for any high-level protocol, that are known to work (or are likely to work) with the sockets produced via Android's Bluetooth and/or WiFi Direct layers?
Right now, I'm not fussy about the specific protocol -- I'm just looking for examples of this sort of protocol layer, to make using these sorts of connectivity options easier for developers.
For example, it looks like I could create a fork or add-on for OkHTTP that uses an alternative source for sockets, and I could probably create a Java HTTP server that does the same. Given those, app developers would write HTTP apps that talked over Bluetooth or WiFi Direct (and, on the client side at least, the coding should be fairly "natural" in feel, once the connectivity-specific pairing and handshaking has gone on).
IOW, going back to dealing with raw sockets feels so two decades ago... :-)
Thanks!
UPDATE
Based on Kristopher Micinski's comment on the ZeroMQ answer, I figured some clarification might be in order.
It's easier to say what I don't want: I don't want to touch sockets, after creating them. Something else at a higher level should handle those for me, plus handle what I'd consider a "protocol" to be (e.g., determining when some communications operation has ended, beyond a socket closing).
Mostly, this is for my book. Most book examples for low-level socket stuff are unrealistic, such as "we open a socket to the server and immediately start blasting the bytes representing some image to be uploaded, then close the socket when we're done". While the examples work, you'd never write something like that in real life:
If you're really working at the socket level, you'd be implementing some protocol that has the hopes of addressing authentication, error handling, etc., even if you're rolling the protocol yourself
Few developers work directly with sockets today for Internet operations
Now, it'd be cool if the protocol offered by the layer were something developers were used to (e.g., HTTP) or had heard of even if they haven't used it (e.g., XMPP). And I'll settle for simple scenarios (e.g., N-way support is cool but not necessary). In this respect, based on preliminary research (conducted by a sleep-deprived brain), ZeroMQ isn't a bad option. It lacks a bit of "brand recognition" compared to, say, an XMPP stack that could work with arbitrary sockets. But off the cuff it seems to meet what else I'm looking for.
I recognize that these stacks will have limitations imposed by the underlying transport (e.g., Bluetooth works well for N-way only for small values of N). And I certainly don't want to portray -- here or in my book -- that whatever solution I portray is the be-all and end-all of socket based communication.
I just want something that has a prayer of being more realistic for actual use. Bonus points if it is something that I can grok, as I have always used higher-level protocols for TCP/IP communications, and so I'm short on experience with direct socket manipulation.

I found ZeroMQ to be useful for managing socket connection. They have a support in multiple languages which includes JAVA. You may use this to manage the sockets once you establish the connection over wifi-direct or BT.

I know it's a somewhat old question and already answered but I would like to contribute.
I did this app: https://play.google.com/store/apps/details?id=com.budius.WiFiShoot and although the WiFi Direct connection n handshake is somewhat broken and it's what causes most of my unhappy users, I'm handling all the communication using the excellent https://github.com/EsotericSoftware/kryonet
and my code is pretty much what you see on their examples, create kryo, register classes, open server, connect client to server IP and shoot objects across with the file information and later I shoot the actual files using this code https://code.google.com/p/kryonet/source/browse/trunk/kryonet/test/com/esotericsoftware/kryonet/InputStreamSenderTest.java
hope it helps.

Related

Implementing an IP Gateway (in Java?)

I'd like to write a program to simulate various network conditions (e.g. latency, packet loss). The most straight-forward presentation of that program would be for it to be configured as an IP gateway - clients send traffic to it either as a default gateway, or downstream routers have it set up as a next-hop for routing purposes.
How can I write a program to receive and process that traffic?
What tools and libraries are available to allow this? e.g. Can this be done through iptables on linux?
(I'd prefer to implement it in Java if possible).
One work around could be to implement such a program as a proxy (e.g. HTTP + SOCKS) and configure a router to send all traffic to the proxy transparently. Another could be to open a raw socket and manually process all the traffic, but this might effectively mean re-implementing a network stack. Is there a better way?
Your question is very broad so the answer will be just as broad. I hope it helps you find some preliminary directions to research.
First, try to avoid writing anything at all. There are existing solutions for this task (hint: search for "WAN Emulator").
If what you find isn't good enough, my next step would be to script something using tc and netem. Linux has very good support for both routing and bridging. Using tc+netem you could add delay, loss, jitter and and just about anything else on top. If needed, create a higher level utility, possibly in Java to configure tc and provide a nicer UI.
A third option would be to actually write something. This is where things get tricky, especially if you want to do it in java. To perform bridging or routing, you'd need to get the frames to user space (iptables+nfqueue could help here), then handle them according to your own logic, and finally write them out using a raw socket. That's quite a lot of work.
Implementing an HTTP proxy would be easier since you don't need to work at the level of individual packets. You can avoid the low level stuff (iptables/nfqueue/raw sockets) and just use plain and simple sockets, or even whole HTTP proxy implementations in Java like this one from Jetty.
If you need further details about some of this stuff, you might want to open a second, more focused question after doing some reading.

Custom UDP protocol encryption without DTLS

Background Info
I'm writing a custom UDP protocol which is targeted for general-purpose use, but will probably be used in a game development setting. My protocol handles all the issues of UDP, reliability, ordering and fragmentation are all handled. I'm using UDP because of the flexibility as I can send some packets unreliable and others reliable.
The Problem
I want my protocol to be encrypted, and I'm also very concerned about MITM. I've read several questions of people who also want to encrypt their UDP protocols and most people recommend DTLS. However the problem with DTLS is that it seems that no one uses it. I can't find decent guides or documentation on how to set up a client/server program for my chosen language (Java). It looks like the only option is bouncycastle, however considering the fact that their client/server test programs won't work with each other, it's probably not a good idea.
I then decided to write the low-level packet receiving and sending code in C and use OpenSSL for the DTLS implementation. I would then call my C code using JNA. However, once again I could not find decent guides or tutorials on how to do DTLS. I could only find two ones which were somewhat helpful, the first one just went over the general C functions to call in which order. I got the impression that your application had to do the client verification yourself and since I have no idea how to do that it wasn't very helpful. The second one was just a raw client/server program which worked when ran but with closer inspection it seems to disable client verification.
The actual question
How would I go about creating my own encrypted transport system over UDP? I read a little about DHKE, but I don't know how to write a good implementation of it in Java using UDP and closer inspection seems that it doesn't prevent MITM. For my specific application I actually probably don't need a key exchange, the clients can actually have the key pair with the server installed beforehand. Would going this route work well? (I would probably just encrypt each packet body with the pair and send it to the server/client)

Java Socket still first choice for TCP/IP programming in Java?

I need to interact with a server over TCP/IP with a basic message/response protocol (so for each request I shall receive a defined response).
In the JVM ecosystem, I think Java Socket was the tool to use 15 years ago, but I'm wondering if there is anything more suitable nowadays in the JDK? For example, with Java Sockets one still needs to manually timeout a request if no answer is received, which feels really old fashioned.
So is there anything new in the JDK or JVM universe?
No, there are much better option nowadays which allow you to implement your client/server asynchronously without additional threading.
Look at SocketChannel from nio or even better AsynchronousSocketChannel from nio2. Check this tutorial
Especially the latter option will allow you to just start the connection listener and register callback which will be called whenever new connection is requested, data arrived, data was written etc.
Also consider looking at some high level solutions like Netty. It will take care of the network core, distribute load evenly to executors. Additionally it provides clears separation of the network layer and processing layer. For the processing layer it will provide you with lot of reusable codecs for common protocols.
You can try RMI which works on top of TCP/IP but hides all the hardwork with a convenient set of APIs.
Follow this tutorial post
Well, there are really a lot of other technologies to use, for example JMS has various implementations which work out of the box.
Sockets are low-level building blocks of network communications, like wires in the electricity network of your house. Yes, they're old fashioned, yes, we likely don't want to see them, but they're there and they will stay there for a good reason.
On top of Sockets, you can e.g. pick the HTTPUrlConnection, which implements most of the HTTP protocol. Still, setting timeout policies are in your hands, which I find quite useful, and extremelly painful at the same time.
http://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/
You are free to move one abstraction level above, and use a ready-made REST library, such as this: http://unirest.io/java.html
The example above connects to a server, configures a HTTP query string, perform the request (timeout, encodings, all the mess under the hood), and finally get the response in Json format in a few lines:
Unirest.post("http://httpbin.org/post")
.queryString("name", "Mark")
.field("last", "Polo")
.asJson();
Nowadays a vast amount of web services are available using REST protocol, which is a simple command-response over HTTP. If you have a chance, I'd suggest using REST, as you can easily find available client and server side implementations, and you don't need to reinvent the wheel on the command-protocol layer either.
On client side, unirest is quite convenient. On the server side, we have had really great experience in the 1.2.xx series of Play! framework. But there are thousands of these things out there, just search for "REST".
Take a look to Netty Project, "Netty is a NIO client server framework which enables quick and easy development of network applications such as protocol servers and clients. It greatly simplifies and streamlines network programming such as TCP and UDP socket server."
This framework give us a lot of capabilities that simplify the programming process, allowing a big scalability.
Is used by Twitter and a lot of big companies in the tecnology industry.
This is a nice presentation from Norman Maurer.

Sockets or RMI - perfomance and scalability

I am currently decide what kind of communication method/network protocol I am going to use for a new project.
What I can tell you about this project is that:
- It is Android/java based, using X amount of Android devices
- These devices should be able to send strings to each other over a local network. We are talking about small strings here. Small as in less than 100 characters.
- The amount of packages/transmissions being sent can vary "A LOT". I can't say how much unfortunately, but the network protocol needs to be as scalable as possible.
I have researched different kinds of possible solutions and is now deciding wether to use "Sockets" or "RMI"
As I have understood about RMI:
It is easier than Java sockets to implement and maintain (smaller amount of code)
It is "a bit slower" than sockets, as it is a new "layer" build on top of Sockets
There may be some scalability issues (if this is true, how "serious" is it?) as it creates a lot of new sockets, resulting in Exceptions.
Obviously the system needs to run as smooth as possible, but the main objective is to make it scalable so it can handle more Android devices.
EDIT: The system the system is not "peer-to-peer". All of the android devices should be able to be configured as the server.
None of your concerns are the real issue, in my view.
RMI has a pre-defined protocol, raw sockets do not.
If you use raw sockets, you have to do all the work to define what messages and protocols are exchanged by client and server.
There are so many good existing protocols (RMI, HTTP, etc.) that I'd wonder why you feel the need to invent your own again.
Android devices communicating over HTTP - tell me why it won't be fast or scalable enough. HTTP is good enough for the Internet - why not you and your solution?
I would suggest you to expose some kind of webservice (SOAP or REST) in your application server. For example, people frequently expose their data to mobile devices as a REST webservice API returning some kind of JSON format in order to make it easier to marshal it again in the client device.
This way you take profit of the underlying implementation of HTTP communication in every application server; any other way, you would have to write your own worker thread pool using nio primitive operations in order to achieve performance... Not a thing to be done in a real production environment - maybe in an academic one?

Implementing push-like technology

I want to be able to exchange data between my app and the server where each side has to be able to initiate sending of data. I want it to happen quickly and polling from the client side for new messages is not fast enough in my case. How do push technologies work?
I was thinking to keep an opened socket connection from the device to the server and send receive raw bytes in some custom format.
Is it a good approach and what problems might I run into? What would you suggest as an alternative?
When it comes to message passing, the time needed to initialize a new connection between the server and the client usually exceeds by far the time needed to sent the data itself - at least for simple status-like messages. This adds significantly to the communication latency, which seems to be your main concern.
There are two main ways to deal with this issue:
Keep a connection open between both ends at all times: This is the standard way of dealing with this issue - it has the advantage of programming simplicity but you may need to use stay-alive packets regularly to keep the connection open. This may reduce the battery life of a mobile device and increase the networking cost slightly. It may also interact unfavorably with the power-management features of a mobile device.
In addition, no matter what you do, you cannot completely eliminate the possibility of a new connection needing to be established at an inconvenient time - connections that are mostly idle do not fare very well in today's networking infrastructure, I'm afraid...
Use a connection-less protocol, such as UDP: This solution has the potential to minimize the communication and power cost, but it requires that your server and client are designed to handle the inherent unreliability of such protocols.
That said, I would not consider the actual format of the data a major concern, until some profiling demonstrates that a custom format will indeed result in significant savings. I would consider the ability to use off-the-shelf network monitoring and analysis software far more important during the development phase...
Push technology is loosely called Comet. The basic logic is to open an persistent HTTP connection with the server (often called HTTP Streaming). As this connection will not last forever (due to the limitations on the server by default), you should be able to reopen the connection. I am not sure how to do it in android specifically but this should be possible.
The basic concept behind this is explained in this blogpost
As this is a concept, it can be implemented in any server side programming language of your choice. This tutorial gives a fair introduction about how to implement COMET in php. socket.io is another such library if you are comfortable with javascript. This SOF thread provides some useful links.
Coming to advantages and disadvantages,
If you want almost instant updates, COMET is the best.
If you have a limit on the number of connections to the server at a time, then COMET probably has to be thought upon based on the tradeoff.

Categories