How to handle tcp inputstream correctly - Java/Android - java

I'm creating an android application that needs a permanent TCP-Connection to a Server.
I've created a Service that establishes the Connection and listens for incoming Bytes on the Inputstream (The service runs in the background).
public class TCPServiceConnection extends Service{
//variables......
//...............
public void onCreate() {
establishTCPConnection():
}
The first 4 incoming bytes symbolize the message-length of a complete Message.
After reading a complete Message from the Inputstream into a separate buffer, I want to call another Service/Asynctask in a separate Thread that analyses the Message. (The service should continue listening for further incoming messages).
public handleTCPInput() {
while(tcp_socket.isConnected()) {
byte[] buffer = readCompletemessagefromTCPInputstream;
calltoAnotherThreadToanalyzeReceivedMessage(buffer);
}
//handle exceptions.......
}
Is there an existing Messagequeue-system in Android/Java that already handles the multi-access onto my separated byte[] buffer ?

To implement this I suggest you start a handler thread which will continuously read from the input stream.
As soon it has read the incoming message, it passes it to main thread using handler.
For eg. handler.sendMessage()
Now since this processing is not a heavy operation you can decide main/UI thread to process this information or you can start a async task to do it.

Related

Passing on a netty ByteBuf (Asynchronous)

I have setup a TCP server using Netty. Now I need to transfer the input of the TCP server (which is a ByteBuf stream from produced by the channel thread) to a separate application thread and I want to do this in a asynchronous fashion where the channel thread writes onto a buffer stream and the application buffer reads from the thread.
I don't want to use the ByteBuf itself as I need to call msg.release() on it and I don't want the channel thread to be waiting for the msg to be consumed by the application thread. Also I can't have the application have its own channel handler.
What data structure in Java should I use that would allow such for my purpose? Is my approach correct or could I use the functionalities provisioned by Netty. InputStreams and OutputStreams also seem the way to do it but wouldn't the channel be waiting if I use them?
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
// Copy the msg's byte[] into a buffer stream and make the application read from the buffer stream
((ByteBuf) msg).release();
}

java: Single socket on read write operation. Full duplex

I have to implement sending data with specific source port and in the same time listen to that port. Full duplex. Does anybody know how to implement it on java. I tried to create separate thread for listening on socket input stream but it doesnt work. I cannot bind ServerSocket and client socket to the same source port and the the same with netty.
It there any solution for dull duplex?
init(){
socket = new Socket(InetAddress.getByName(Target.getHost()), Target.getPort(), InetAddress.getByName("localhost"), 250);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
}
private static void writeAndFlush(OutputStream out, byte[] b) throws IOException {
out.write(b);
out.flush();
}
public class MessageReader implements Runnable {
#Override
public void run() {
//this method throw exception EOF
read(in);
}
private void read(DataInputStream in){
while (isConnectionAlive()) {
StringBuffer strBuf = new StringBuffer();
byte[] b = new byte[1000];
while ((b[0] = bufferedInputStream.read(b)) != 3) {
strBuf.append(new String(b));
}
log.debug(strBuf.toString());
}
}
}
What you're trying to do is quite strange: A ServerSocket is a fully implemented socket that accepts connections, it handles its own messages and you definitely cannot piggy-back another socket on top of it.
Full duplex is fairly simple to do with NIO:
Create a Channel for your Socket in non-blocking mode
Add read to the interest OPs
Sleep with a Selector's select() method
Read any readable bytes, write any writable bytes
If writing is done, remove write from interest OPs
GOTO 3.
If you need to write, add bytes to a buffer, add write to interest OPs and wake up selector. (slightly simplified, but I'm sure you can find your way around the Javadoc)
This way you will be completely loading the outgoing buffer every time there is space and reading from the incoming one at the same time (well, single thread, but you don't have to finish writing to start reading etc).
I had run into the same question and decided to answer it myself. I would like to share with you guys the code repo. It is really simple, you can get the idea to make your stuff work. It is an elaborate example. The steps accidentally look like Ordous's solution.
https://github.com/khanhhua/full-duplex-chat
Feel free to clone! It's my weekend homework.
Main thread:
Create background thread(s) that will connect to any target machines(s).
These threads will connect to target machines and transmit data and die
Create an infinite loop
Listen for incoming connections.
Thread off any connection to handle I/O
Classes:
Server
Listens for incoming connections and threads off a Client object
Client
This class is created upon the server accepting the incoming connection, the TcpClient or NetClient (i forget what java calls it) is used to send data. Upon completion it dies.
Target
Is created during the start up and connects to a specific target and send data.
once complete it dies.

Java Processing Messages Asynchronously in EJB Listener

I have a EJB Singleton that constantly listens for messages as a String and when a message arrives it processes the message for example storing to the database and doing other things.
Once I receive the message and after furthing processing, I need to asycnhrnously send the message. Java provides the ExecuteService to asynchronusly process the message. EJB also provides asynchronously processing through the #Asynchrnous annotation. The listener works by checking every couple of seconds to see if the message has arrived. Once the asynchronous method has been sent, a reply would come back in the form of an InputStream. I have two queries:
I have sample code:
#Startup
#Singleton
public class Processor {
#PostConstruct
public void init() {
while(true) {
Thread.sleep(1000);
if(!portIsOpen()) {
openPort();
listen();
}
else {
listen();
}
}
}
public void listen() {
// listens for messages, once the message arrives process them and then send asynchronously
Future<InputStream> inputStream = processAsynchrnously();
while(!inputStream.isDone()) {
// carry on with repeated requests
}
inputStream = inputStream.get();
// read this inputStream and turn into XML
}
#Asynchronous
public Future<InputStream> processAsynchronosly() {
// make an http connection and send the request of with the data as XML
return new AsychResult<InputStream>(httpUrlConnection.getInputStream());
}
}
The above is what I am trying to achive. However, the aim is to send the request asynchrnously and not wait but continue to receive other requests repeatly. The problem is the while(!inputStream.isDone()) this means it is blocked.
1) How can this be implemented in a different way so the while loop is not required.
2) When the data is available so the input stream is returned with the XML, in EJB is there a listener that can be invoked so that I will implement a method that will read the contents of the input stream? I am aware there are Inceptors but an Inceptor will not work in this case.
EDIT:
Please note the application is a TCIIP application, so it listens for messages on a port. It is not a RMI-IIOP application. This Singleton acts as a listener, so when the message arrives it processes it.
If MDB is the only solution how will MDB help? Could you show a code sample?

Synchronizing methods in RXTX

Situation:
I'm trying to make the incoming data from SerialPort usefull for my purposes. In one class Processor.java I've implemented several methods - one of them (serialEvent) implements gnu.io.SerialPortEventListener. It stores the information read from inputStream in a buffer which is a byte array. There is also a method, which writes data to outputStream.
Problem:
I want to implement a method (in the same class) which will write something to outputStream depending on the messages read from the inputStream.
Pseudo code:
#Override
public void serialEvent(SerialPortEvent event) {
// get data
}
public void writeData(String dataToWrite) {
// write data
}
public void respond() {
// write data
// wait for appropriate response (read data)
// write data
// ...
}
How can I do this?
Only thing that comes to mind is a background thread that waits for input-buffer-full condition to process the received message and responds to it.
If you are communicating in fixed length packets or start-stop marked packets you should create a thread that would monitor the serial port, buffer the received data and once a "packet/message complete" condition is met to fire an event to a registered listener (in another thread if possible). That listener would then process the message and respond (in its own thread).

How can I implement threads in this scenario?

I haven't got any code at the moment but I have a situation where I will be implementing an Java application onto a wireless sensor. There can only be one main method.
There will be multiple other wireless sensors that can connect to my sensor. My sensor needs to do a calculation based on thhe information provided to me by the other sensors. Each sensor can choose whether or not they want to participate in the calculation. Every 1 second, my sensor does a calculation.
So basically, what I need is to listen for incoming sensors, provide them with a thread to interact with, and retrieve the information from each sensor.
My question is, in my application, how do I listen for incoming sensors (blocking call) and also free my application to carry out its calculations?
From a high level, this is what your application will do
==Main Thread==
start socket
Start processing thread
accept an incoming connection (this will cause the thread to block until a connection occurs)
start new thread to handle socket (handler thread) (alternatively use a thread pool, but that is more complicated)
return to 3
==Handler Thread==
Receive open socket from main thread
Save data coming in from socket to be given to processing thread
Finish and close socket
==Processing Thread==
Wait 1 second
Process data retrieved from step 2 of Handler Thread
Return to 1
You need another thread that receives the information of all the communication threads. You should look at the utilities in java.util.concurrent such a BlockingQueue that let threads pass data to one another thread-safely.
Most of all you should read a lot about multi-threading: it is not a trivial topic.
This will get you started. Add error/exception checking/handling as necessary.
public class Test {
static class WorkTask42 implements Runnable {
public void run() {
// background work
}
}
public static void main(String... args) throws Exception {
// repeat for each background task
WorkTask42 wt = new WorkTask42();
Thread a = new Thread(wt);
a.setDeamon(true);
a.start();
}
}

Categories

Resources