我目前正在为android开发一款游戏。这个游戏有大量的网络。
最好是有两个单独的线程,一个用于接收消息,另一个用于发送消息。还是只有一个线程来发送和接收消息更好?
public static void init(String h){
host=h;
connected=false;
instance = new Client();
new Thread(new Runnable() {
@Override
public void run() {
group = new NioEventLoopGroup();
try{
bootstrap = new Bootstrap()
.group(group)
.channel(NioSocketChannel.class)
.handler(instance);
channel = bootstrap.connect(host,PORT).sync().channel();
connected=true;
} catch (Exception e) {
if (notifier!=null){
notifier.onServerNoLongerReachable();
}
e.printStackTrace();
}
}
}).start();
}
public static void setNotifier(ClientInterface notif){
notifier = notif;
}我使用的是Netty,并且我的活动实现了一个自定义接口
public interface ClientInterface{
void onReceive(String msg);
void onServerNoLongerReachable();
}发布于 2017-04-09 16:18:55
对于Android Dev来说,使用Thread不是一个好的做法。最好使用异步任务:https://developer.android.com/guide/components/processes-and-threads.html
或者作为Cricket_007,你应该看看RxJava:https://github.com/ReactiveX/RxAndroid
对于networkCall,您可以使用Retrofit w/ RxJava:http://square.github.io/retrofit/
https://stackoverflow.com/questions/43304281
复制相似问题