2017-04-09 50 views
1

我目前正在为android开发一款游戏。这场比赛有沉重的网络。好的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(); 
} 
+0

一个线程将是理想,但是你目前遇到什么问题来提示这个问题?你使用的是'RxJava',因为这将有助于网络请求。 –

+0

我目前没有遇到任何问题,我只是验证我不会以错误的方式解决问题。 – logan20

+0

你可以提供任何代码作为例子吗? –

回答

0

使用线程不是Android开发一个很好的做法自定义界面。 使用的AsyncTask更好:https://developer.android.com/guide/components/processes-and-threads.html

或者作为Cricket_007你应该看看RxJava:https://github.com/ReactiveX/RxAndroid

对于networkCall,你可以使用改造瓦特/ RxJava: 每封邮件http://square.github.io/retrofit/

+0

但是,这并没有真正回答这个问题,因为1)AsyncTask需要小心处理Socket/Channel通信。 2)问题中的'NioEventLoopGroup'需要有一个等价的Rx,所以只需指向文档就不会有帮助 –