gpt4 book ai didi

java - 参数中的0有什么意义--String message=new String(recievepacket.getData(),0,recievepacket.getLength());

转载 作者:行者123 更新时间:2023-12-02 01:51:49 25 4
gpt4 key购买 nike

如果我使用任何其他数字而不是 0,我将看不到任何消息。为什么在将接收到的数据包转换为字符串时使用0?

public class UdpClient {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
DatagramSocket cs=new DatagramSocket();
byte [] recievedata=new byte[512];
String message=null;
byte [] senddata=new byte[512];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("client created");
InetAddress addr=InetAddress.getByName("127.0.0.1");
int port=9003;

while(true) {

System.out.println( "client says");
message=br.readLine();

senddata=message.getBytes();
DatagramPacket sendpacket=new DatagramPacket(senddata, senddata.length, addr, port);
cs.send(sendpacket);

DatagramPacket recievepacket=new DatagramPacket(recievedata, recievedata.length);
cs.receive(recievepacket);
message=new String(recievepacket.getData(), 0,recievepacket.getLength());
System.out.println("server says"+message);

}

}
}

最佳答案

参见the javadoc String 类:

String(byte[] bytes, int offset, int length)

Parameters:
bytes - The bytes to be decoded into characters
offset - The index of the first byte to decode
length - The number of bytes to decode

关于java - 参数中的0有什么意义--String message=new String(recievepacket.getData(),0,recievepacket.getLength());,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52868542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com