Domanda

I am creating an android service which is always running and listening messages from socket. But it doesn't work with good performance and i am looking for some nio alternative or tutorial.

What is the best way for listening a socket for all time ?

Does AndroidAsync support standart sockets ? https://github.com/koush/AndroidAsync

Is there anyone used Apache Mina ? I am having character problem with Mina. http://mina.apache.org/

Or how can i do this job with good performance using standart sockets

Waiting for your experiences.

Thanks

È stato utile?

Soluzione

The normal way to get decent performance from a socket (for int read() and write(int)) is to use a buffered stream / reader / writer. That reduces the number of system calls and makes byte or character at a time I/O much faster.

I don't expect that using NIO will make a significant difference. If the problem is not buffering, then (IMO) it is probably a network bandwidth and/or latency issue. If that is the case, there is little that you can do in Java that would make much difference.

Altri suggerimenti

I have some convenience methods for writing strings with java.nio:

private static Charset charset;
static
{
    charset = Charset.forName("UTF-8");
}

public static void writeString(SocketChannel sc, String string) throws IOException {
    CharBuffer c = CharBuffer.wrap(string);
    ByteBuffer b = charset.encode(c);
    b.compact();
    b.flip();
    sc.write(b);
}

public static String readString(SocketChannel sc) throws IOException {
    ByteBuffer bbuf = ByteBuffer.allocate(8096);
    sc.read(bbuf);
    bbuf.flip();
    CharBuffer cbuf = charset.decode(bbuf);
    return cbuf.toString();
}

All you need to do is establish your SocketChannel connections and you can use these all you want. java.nio is really not that difficult once you get used to it :)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top