我如何从线程返回值

时间:2018-10-03 16:01:11

标签: java android android-studio

我有一个灯泡,在手册中他们说我需要通过UDP发送请求。因此,我创建了可以发送和接收所需信息的类。当我尝试直接从main发送/获取请求时,studio会说我无法从主线程使用网络,因此我将send / obtain方法放入线程。现在我不明白如何从线程返回任何值。请帮忙。谢谢。

package com.bulbs;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class udpHelper {
    public void sendRequest(final String host, final String command, final int port) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                byte[] message = command.getBytes();
                try {
                    InetAddress address = InetAddress.getByName(host);
                    DatagramPacket packet = new DatagramPacket(message, message.length, address, port);
                    DatagramSocket dsocket = new DatagramSocket();
                    dsocket.send(packet);
                    dsocket.close();
                    System.out.println("Sent");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }


    public void receiveRequest(final int port) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    DatagramSocket dsocket = new DatagramSocket(port);
                    byte[] buffer = new byte[2048];
                    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                    while (true) {
                        dsocket.receive(packet);
                        String msg = new String(buffer, 0, packet.getLength());
                        System.out.println(packet.getAddress().getHostName() + " : " + msg);
                        packet.setLength(buffer.length);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }
}

0 个答案:

没有答案