当前位置:  开发笔记 > 编程语言 > 正文

与equals()的Java字符串比较与UDP无法正常工作

如何解决《与equals()的Java字符串比较与UDP无法正常工作》经验,为你挑选了1个好方法。

我试图通过UDP发送消息并将其与字符串文字进行比较,但它似乎不起作用.

这是UDP服务器代码

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

public class Controller {

    public static void main(String args[]) {


        //create UDP server
        try {
            DatagramSocket socket = new DatagramSocket(5002);
            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

            //wait for done message
            socket.receive(packet);
            String msg = new String (packet.getData());
            if(msg.equals("Done"))
            {
                System.out.println("Done received");
            }
            else {
                System.out.println("Done not received");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

这是UDP客户端代码

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

public class Slave {

    public static void main(String args[]) {
        //create UDP client
        try {
            DatagramSocket socket = new DatagramSocket();
            byte[] buffer;

            //send Done message
            buffer = "Done".getBytes();
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getLocalHost(), 5002);
            socket.send(packet);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

即使已完成消息发送,我得到的输出也是"未收到".代码有什么问题?



1> Tobias Geise..:

问题是,您正在声明一个1024字节的缓冲区,您将转换为字符串.该字符串不等于"完成",它只是"太长".您必须获取已发送数据的实际长度.您可以在以下方面执行以下操作Controller:

public class Controller {

    public static void main(String args[]) {


        //create UDP server
        try {
            DatagramSocket socket = new DatagramSocket(5002);
            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

            //wait for done message
            socket.receive(packet);

            //Get actual data length and copy it
            byte[] data = new byte[packet.getLength()];
            System.arraycopy(packet.getData(), packet.getOffset(), data, 0, packet.getLength());

            //Create string from actual data
            String msg = new String (data);
            if(msg.equals("Done"))
            {
                System.out.println("Done received");
            }
            else {
                System.out.println("Done not received");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

推荐阅读
郑谊099_448
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有