我试图通过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(); } } }
即使已完成消息发送,我得到的输出也是"未收到".代码有什么问题?
问题是,您正在声明一个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(); } } }