【问题标题】:How to listen for incoming messages from sockets of threads to update a Listview in android?如何侦听来自线程套接字的传入消息以更新 android 中的 Listview?
【发布时间】:2015-04-04 17:18:02
【问题描述】:

我正在开发一个 android 应用程序,我必须在其中创建与一台服务器的多个客户端连接。在服务器端,我正在为每个客户端创建一个新线程,它工作正常,但是在我正在侦听来自套接字的消息并更新在片段中创建的列表视图的新创建线程中,它没有得到更新。请帮我解决这个问题。

public class ClientSocketHandler extends Thread {

 private static final String TAG = "ClientSocketHandler";
 //private Handler handler;
// private ChatManager chat;
 private InetAddress mAddress;
 InputStream dataInputStream=null;
 OutputStream dataOutputStream=null;
 static String msgToSend="";
 int i;
 char c;
 String newMsg="";
 Boolean flag=true;
 WiFiChatFragment frg;  
 Handler handler;
 public ClientSocketHandler(InetAddress groupOwnerAddress) {
 this.mAddress = groupOwnerAddress;
 //this.handler=handl;
  }
 @Override
 public void run() {
 Socket socket = new Socket();
 try {
 socket.bind(null);
 socket.connect(new InetSocketAddress(mAddress.getHostAddress(),
 WiFiServiceDiscoveryActivity.SERVER_PORT), 5000);

 Log.d(TAG, "Launching the I/O handler");
    dataInputStream = socket.getInputStream();
    dataOutputStream = socket.getOutputStream();


    while (true) {
        while(flag){
            if((i=dataInputStream.read())!=1){

                frg.pushMessage(newMsg);
                newMsg="";
                flag=false;
            }
            else{
            c=(char)i;
            newMsg+=c;}

        }
    if(!msgToSend.equals("")){
             dataOutputStream.write(msgToSend.getBytes());
             dataOutputStream.flush();
             msgToSend = "";
            }

    }
 } catch (IOException e) {
 e.printStackTrace();
 try {
 socket.close();
 } catch (IOException e1) {
 e1.printStackTrace();
 }
 return;
 }
 }

 public static void sendMsg(String msg){
           msgToSend = msg;
 }


}

【问题讨论】:

    标签: android sockets client server


    【解决方案1】:

    我认为这可能发生在以下任何未处理的情况下。 1.设置适配列表 2. 检查客户端是否接收到数据并添加到数据源。 3. 将数据添加到ListView的数据源后调用notifyDataSetChanged()。

    【讨论】:

    • 列表在片段中。当连接建立时,片段开始,我将从套接字的输入流接收到的消息发送到该片段的函数,该函数将通知适配器。
    • @Fari 在构造函数中将 Handler 引用传递给 ClientSocketHandler 线程,并通过 Handler 引用发送消息,在 Fragment 中,您将在 handleMessage(Message msg) 方法中获取发送的消息。您需要将此消息添加到 List 或 ArrayList 中,然后调用 notifyDataSetChanged() 来更新 UI。
    • 我对句柄消息方法很熟悉。但是我怎样才能将消息从这个线程传递到那个句柄消息函数呢??
    • 还有一个问题。我如何从该片段的文本视图中发送消息到该线程的进程中以将其发送到服务器?
    • 将你的构造函数修改为 public ClientSocketHandler(InetAddress groupOwnerAddress, Handler handle) { this.mAddress = groupOwnerAddress; this.handler=句柄; } \n 并使用以下代码通过处理程序消息从线程发送消息 msgObj = handler.obtainMessage();捆绑 b = 新捆绑(); b.putString("消息", msg); msgObj.setData(b); handler.sendMessage(msgObj);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-13
    • 2014-07-09
    • 1970-01-01
    • 2017-07-16
    • 1970-01-01
    • 2010-12-04
    • 1970-01-01
    相关资源
    最近更新 更多