-1

我正在尝试制作一个能够向计算机发送消息并从中接收消息的 Android 应用程序。这是非常基本的。问题是,我已经通过多播实现了这一点,尽管并不完全如此。我的应用程序能够从计算机接收消息(它使用我制作的 java 应用程序来接收和发送消息)。但是,当我尝试从设备向计算机发送消息时,消息不会到达计算机。我的意思是,应用程序。

桌面应用程序和 Android 应用程序都使用相同的客户端 - 服务器类。这就是让我如此困惑的原因。因为,当我使用相同的类时,为什么它以一种方式工作而不是另一种?我只是不不。

桌面应用程序在 Windows 上运行。

此外,当 Android 应用程序收到一条消息时,它会通过以下方式接收它:“Message 1����������������������������... " 何时应收到消息:"消息 1"。我不知道这是否相关。

代码如下:

服务器类:

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

public class MulticastSocketServer implements Runnable{

    final static String INET_ADDR = "224.0.0.3";
    final static int PORT = 8888;
    static String msg;

    public MulticastSocketServer(String message) throws UnknownHostException, InterruptedException {
        msg = message;
        Thread thread = new Thread(this);
        thread.start();
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        // Get the address that we are going to connect to.
        InetAddress addr = null;
        try {
            addr = InetAddress.getByName(INET_ADDR);
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // Open a new DatagramSocket, which will be used to send the data.
        try (DatagramSocket serverSocket = new DatagramSocket()) {

            msg += "\\0";

            for (int i = 0; i < 10; i++) {
                // Create a packet that will contain the data
                // (in the form of bytes) and send it.
                DatagramPacket msgPacket = new DatagramPacket(msg.getBytes(),
                        msg.getBytes().length, addr, PORT);
                serverSocket.send(msgPacket);

                System.out.println("Server sent packet with msg: " + msg);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            serverSocket.disconnect();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

客户端类:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;

public class MulticastSocketClient implements Runnable {

    final static String INET_ADDR = "224.0.0.3";
    final static int PORT = 8888;
    Connection360 conn;

    public MulticastSocketClient (Connection360 connection) throws UnknownHostException {
        conn = connection;
        Thread thread = new Thread(this);
        thread.start();
    }

    @Override
    public void run() {
        try{
            // Get the address that we are going to connect to.
            InetAddress address = InetAddress.getByName(INET_ADDR);

            // Create a buffer of bytes, which will be used to store
            // the incoming bytes containing the information from the server.
            // Since the message is small here, 256 bytes should be enough.
            byte[] buf = new byte[256];

            // Create a new Multicast socket (that will allow other sockets/programs
            // to join it as well.
            try (final MulticastSocket clientSocket = new MulticastSocket(PORT)){
                //Joint the Multicast group.
                clientSocket.joinGroup(address);

                System.out.println("Connected");

                //while (true) {
                    // Receive the information and print it.
                    DatagramPacket msgPacket = new DatagramPacket(buf, buf.length);
                    Timer timer = new Timer("tmr");
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            clientSocket.disconnect();
                        }
                    },10000);
                    clientSocket.receive(msgPacket);

                    String msg = new String(buf, 0, buf.length);
                    System.out.println("Socket 1 received msg: " + msg.substring(0, msg.indexOf("\\0")));
                    conn.MessageReceived(msg.substring(0, msg.indexOf("\\0")));
                    clientSocket.disconnect();
                //}
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            }catch (UnknownHostException ex){

            }
    }
}

这个类是我为桌面应用程序制作的。我为 Android 应用程序制作的类是相同的,但我必须将其更改System.out.println()Log.v(). 至于其他的,一模一样。

因此,如果您碰巧知道会发生什么,我将非常感谢您在该主题方面的帮助。

谢谢!

4

1 回答 1

0

当您读取传入的数据包时,您不使用它的大小,而是使用缓冲区的大小:

String msg = new String(buf, 0, buf.length);
// should be:
String msg = new String(buf, 0, msgPacket.getLength());
// or even better:
String msg = new String(msgPacket.getData());

如果传入的数据包较短,则缓冲区的其余部分包含您得到的随机数据。Java 字符串不是以 NUL 结尾的,因此msg.indexOf("\\0")不起作用。

于 2015-07-24T01:30:28.217 回答