如何正确比较从数据报包收到的字符串值?

时间:2016-04-27 16:34:09

标签: java string datagram

我正在制作一个简单的客户端服务器程序。当客户端发送字符串" start"时,我希望服务器开始执行一些代码。现在,我让客户端发送带有消息" start"的数据报包,服务器从数据包中获取字节缓冲区,将其转换为字符串,然后将该字符串值与字符串文字& #34;开始&#34 ;.显然,我做错了,因为我的代码永远不会进入if(sentence.equals(start){ System.out.println("ok");}的for循环

我的代码:

public static void main(String args[]) throws IOException{


    byte[] receiveData;
    byte[] sendData;
    DatagramSocket serverSocket = new DatagramSocket(2014);


    while(true){

        receiveData = new byte[15];
        DatagramPacket frame = new DatagramPacket(receiveData, receiveData.length);
        serverSocket.receive(frame);
        InetAddress IPaddress = frame.getAddress();
        System.out.println("INET " + IPaddress);


        byte[] data;

        int port = frame.getPort();
        System.out.println("port " + port);

        String sentence = new String(frame.getData());
        String start =  new String("start");


        System.out.println("RECEIVED FROM CLIENT: " + sentence);


        if(sentence.equals(start)){
            System.out.println("ok");
        }
    }
}

1 个答案:

答案 0 :(得分:2)

进行以下更改。

    String sentence = new String(frame.getData(), 0, frame.getLength());