我正在尝试通过UDP在一个数据包中发送多个值。我使用ByteArrayOutputStream
将字节写入字节数组,并使用ByteArrayInputStream
在服务器端读取这些值。问题是我可以写入ByteArrayOutputStream
且可以正确读取的最大值是255,但是我需要发送更大的值。这是我在服务器端的代码
public class Server implements Runnable {
private DatagramSocket socket;
private boolean running;
private byte[] buf = new byte[1024];
public Server() throws SocketException {
socket = new DatagramSocket(4445);
}
@Override
public void run() {
while (true) {
try {
DatagramPacket packet
= new DatagramPacket(buf, buf.length);
socket.receive(packet);
ByteArrayInputStream bInput = new ByteArrayInputStream(buf);
System.out.println(bInput.read());
System.out.println(bInput.read());
} catch (IOException e) {
}
}
}
}
以及客户端
public class Main {
private static InetAddress ip;
public static void main(String[] args) throws IOException {
ip = InetAddress.getLocalHost();
Runnable server = new Server();
new Thread(server).start();
DatagramSocket ds = new DatagramSocket();
byte[] data = new byte[1024]; // Max length
DatagramPacket packet = new DatagramPacket(data, data.length);
packet.setAddress(ip);
packet.setPort(4445);
ByteArrayOutputStream ba = new ByteArrayOutputStream();
as.write(5);
as.write(300);
packet.setData(ba.toByteArray());
ds.send(packet);
}
}
所以我可以从ByteArrayInputStream
中获得数字5,但任何大于255的值均会被错误地恢复。