写了两个类,一个是发送端,一个是接收端。
接收端写了两个字符串,为什么用dp.getData().length这个就打不出来后面的部分呢?
查了一下 .length这个是1024,创建新String时候如果空格太多就自动中止吗?另外getLength()为什么能直接是12呢?
输出:
hello world! from 192.168.31.204 port 9999
hello world!
程序:
package com.network;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class ServerTest {
public static void main(String[] args) throws Exception {
byte[] buf = new byte[1024];
DatagramSocket ds = new DatagramSocket(8891);
DatagramPacket dp = new DatagramPacket(buf,1024);
ds.receive(dp);
String str1 = new String(dp.getData(),0,dp.getLength())+" from "+dp.getAddress().getHostAddress()+" port "+dp.getPort();
System.out.println(str1);//正常
String str2 = new String(dp.getData(),0,dp.getData().length)+" from "+dp.getAddress().getHostAddress()+" port "+dp.getPort();
System.out.println(str2); //这里返回的就不带from和后面那一截了,为什么呢?
ds.close();
}
}
package com.network;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class ClientTest {
public static void main(String[] args) throws Exception {
String str = "hello world!";
byte[] buf = new byte[1024];
DatagramSocket ds = new DatagramSocket(9999);
DatagramPacket dp = new DatagramPacket(str.getBytes(), str.getBytes().length, InetAddress.getLocalHost(), 8891);
ds.send(dp);
ds.close();
}
}