草庐IT

java - Android:与工作线程通信以发送消息

coder 2023-09-18 原文

我正在尝试通过 tcp 从一个 android 设备向另一个设备发送消息。发送设备发送到用作服务器的 PC,然后将消息发送到其他设备。 为了接收消息,我运行了一个与 UI 线程并行的线程,该线程使用处理程序更新用户界面以显示消息。这很好用。

现在我正在使用 AsyncTask 发送消息,它创建一个套接字,然后发送消息,然后再次关闭套接字。所以每次我想发送消息时,我都必须连接和断开连接。

public class SendTask extends AsyncTask<String, Void, Void> {

static final String TAG = "SendTask";

private Socket soc;
private String theIp;
private int thePort;

public SendTask(String pIp, int pPort){
    theIp = pIp;
    thePort = pPort;
}

@Override
protected Void doInBackground(String... arg0) {

    try {
        soc = new Socket(theIp, thePort);
        soc.getOutputStream().write(arg0[0].getBytes());
        soc.close();
    } catch (Exception e) {
        Log.d(TAG, "failed to create socket");      
        e.printStackTrace();
    }

    return null;
}

}

我宁愿有一个解决方案,我创建一个线程来打开套接字,然后每次单击按钮时发送从 EditText 接收的文本。是否有类似接收线程的解决方案?我正在努力解决如何告诉创建的线程何时发送消息而不从该线程访问 UI 的问题。

发送线程如下所示:

public class ReceiveClient implements Runnable {

static final String TAG = "ReceiveClient";

public static final int NEW_INPUT = 101;

private Socket soc;
private String theIp;
private int thePort;
Handler handler;

public ReceiveClient(String pIp, int pPort, Handler pHandler){
    this.theIp = pIp;
    this.thePort = pPort;
    handler = pHandler;
}

@Override
public void run() {
    Log.d(TAG, "try to create socket");
    try {
        soc = new Socket(theIp, thePort);
    } catch (Exception e) {
        Log.d(TAG, "failed to create socket");      
        e.printStackTrace();
    }
    Log.d(TAG, "running");
    try {
        while (!Thread.currentThread().isInterrupted()) {
            byte b[] = new byte[16];
            int count = soc.getInputStream().read(b, 0, 16);
            if(count > 0){
                String s = new String(b);
                Log.d(TAG, "received: " + s);
                displayMessage(s);
                }
            }
        Log.d(TAG, "done");
        }catch (Exception e) {
            System.err.println(e);
    }
}

private void displayMessage(String text){
    Message msg = handler.obtainMessage();
    msg.what = NEW_INPUT;
    msg.obj = text;
    handler.sendMessage(msg);
}
}

最佳答案

我建议你使用某种阻塞队列。在单独的线程中处理读取和写入 - 这是线程安全的,即如果一个线程从套接字读取而另一个线程写入它,则不会发生任何冲突。

您的阅读器线程需要改进 - InputStream.read 将在没有可用输入时阻塞,因此您的 Thread.isInterrupted 检查没有用。相反,我建议您跳过 isInterrupted 检查并在您想要停止阅读时关闭套接字,这将导致您的 read() 解锁。

在你的作者线程中做这样的事情

 private ArrayBlockingQueue<String> writerQueue = new ArrayBlockingQueue<String>( 10 );
 private String stopSignal = "whatever";       

 public void stopWriter() { // this can safely called from other threads and will cause writer thread to stop
     writerQueue.put( stopSignal );     
 } 

 // this can also safely called from other threads
 public void sendMessage( String newMessage ) {
     writerQueue.put( newMessage );
 }

 @Override
 public void run() {
     String currentMessage = writerQueue.take(); // if there are no messages in queue this will block
     if( currentMessage == stopSignal ) // == comparison here is correct! we want to check for object equality 
         return; // stop signal received
     // write your string here
 }  

在您的 UI 中使用发送消息

writerThread.sendMessage( "Whatever you want to send );

完成线程后用

writerThread.stopWriter();

关于java - Android:与工作线程通信以发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25931649/

有关java - Android:与工作线程通信以发送消息的更多相关文章

  1. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  2. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  3. ruby-on-rails - Rails 应用程序之间的通信 - 2

    我构建了两个需要相互通信和发送文件的Rails应用程序。例如,一个Rails应用程序会发送请求以查看其他应用程序数据库中的表。然后另一个应用程序将呈现该表的json并将其发回。我还希望一个应用程序将存储在其公共(public)目录中的文本文件发送到另一个应用程序的公共(public)目录。我从来没有做过这样的事情,所以我什至不知道从哪里开始。任何帮助,将不胜感激。谢谢! 最佳答案 无论Rails是什么,几乎所有Web应用程序都有您的要求,大多数现代Web应用程序都需要相互通信。但是有一个小小的理解需要你坚持下去,网站不应直接访问彼此

  4. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  5. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  6. ruby-on-rails - rspec should have_select ('cars' , :options => ['volvo' , 'saab' ] 不工作 - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion在首页我有:汽车:VolvoSaabMercedesAudistatic_pages_spec.rb中的测试代码:it"shouldhavetherightselect"dovisithome_pathit{shouldhave_select('cars',:options=>['volvo','saab','mercedes','audi'])}end响应是rspec./spec/request

  7. ruby-on-rails - s3_direct_upload 在生产服务器中不工作 - 2

    在Rails4.0.2中,我使用s3_direct_upload和aws-sdkgems直接为s3存储桶上传文件。在开发环境中它工作正常,但在生产环境中它会抛出如下错误,ActionView::Template::Error(noimplicitconversionofnilintoString)在View中,create_cv_url,:id=>"s3_uploader",:key=>"cv_uploads/{unique_id}/${filename}",:key_starts_with=>"cv_uploads/",:callback_param=>"cv[direct_uplo

  8. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  9. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  10. jquery - 我的 jquery AJAX POST 请求无需发送 Authenticity Token (Rails) - 2

    rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送

随机推荐