Answer the question
In order to leave comments, you need to log in
Why not convert to a string using the getData() method?
Hello, I’m trying to make a primitive UDP server in java, I did everything as in the examples, but I can’t get the data of the packet itself (I get everything else like the length of the mix) instead of data, just an empty string comes in, and I can’t understand what the problem is, below is the code (Debug .addDeb is the same as System.out.println)=>
// Отправка сообщения =>
try {
socket = new DatagramSocket();
while(true) {
// Создаем данные =>
int i = 1;
byte [] buf = new byte[i];
// Иницилизация адресса и порта =>
InetAddress addr = InetAddress.getByName("localhost");
int port = 5588;
// Создание и отправка пакета =>
packet = new DatagramPacket(buf, buf.length, addr, port);
socket.send(packet);
Debug.addDeb("Пакет отправлен...", label);
}
} catch (IOException e) {
e.printStackTrace();
}
// Принятие сообщения (это уже другой файл и запускаю его я отдельно как программу)=>
try {
byte [] buf = new byte[10000];
packet = new DatagramPacket(buf, buf.length);
socket = new DatagramSocket(5588);
Debug.addDeb("Сервер создан и прослушивает порт:" + socket.getLocalPort(), label);
while(true) {
buf = new byte[10000];
Debug.addDeb("Ожидаем пакета...", label);
socket.receive(packet);
Debug.addDeb("Пакет пришел, его длина: " + packet.getLength(), label);
String s = new String(packet.getData(), 0, packet.getLength());
Debug.addDeb(s, label);
}
} catch (IOException e) {
e.printStackTrace();
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question