java - Read and write from a socket simultaneously -
java - Read and write from a socket simultaneously -
i'm writing android app in java , want create listener receive messages in while(true)
loop, , able send messages server. task i'm using sockets asynctask
. have written connectionhandler
class handle send , receive requests app.
so far good, working fluently sending , receiving messages 1 @ time, couldn't find way simultaneously.
i need execute next code in thread, don't know how it, because have homecoming string
:
public static string receive() { seek { homecoming mconnectionhandler.new asyncreceivefromserver().execute() .get(); } grab (interruptedexception e) { e.printstacktrace(); } grab (executionexception e) { e.printstacktrace(); } homecoming null; } private class asyncreceivefromserver extends asynctask<void, void, string> { @override protected string doinbackground(void... params) { string result = null; seek { result = in.readline(); } grab (ioexception e) { e.printstacktrace(); } homecoming result; } }
when i'm running receive function in while(true)
loop, can't send messages, because ...execute().get()
blocking java class connectionhandler
.
so sum up, how can execute above code in thread or other asynchronous way? or maybe have other suggestion run send , receive simultaneously while receive while(true)
loop?
first off- never utilize execute.get(). if think need utilize it, you're architected wrong- breaks entire point of using thread have calling thread wait result. if phone call execute, you'll run on thread , work fine. if need more 1 thread running simultaneously, utilize executeonexecutor() override 4.0 shared thread pool mechanism of asynctask.
or improve yet- don't utilize asynctask this. have want run forever, waiting input remote connection. improve fit thread asynctask. i'd go thread , have while loop built thread, , have thread terminate when connection closed.
java android multithreading sockets
Comments
Post a Comment