我试图传达两个java程序,没问题。程序A发送带有"令牌"的消息。和程序B接收消息并打印出来。我遇到的问题是我想在消息长度发送到程序B之前创建具有准确长度的数组,但我不知道我该怎么做。
public class ProgramA {
public static void main(String[] args) {
try {
DatagramSocket datagramSocket = new DatagramSocket();
String message = "token";
InetAddress addr = InetAddress.getByName("localhost");
DatagramPacket datagram = new DatagramPacket(message.getBytes(),message.getBytes().length, addr, 5556);
datagramSocket.send(datagram);
datagramSocket.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
public class ProgramB {
public static void main(String[] args) {
try {
InetSocketAddress addr = new InetSocketAddress("localhost", 5556);
DatagramSocket datagramSocket = new DatagramSocket(addr);
byte[] message = new byte[5];
DatagramPacket datagram = new DatagramPacket(message, message.length);
datagramSocket.receive(datagram);
datagramSocket.close();
for(int i = 0; i < message.length; i++) {
System.out.print((char)message[i]);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
答案 0 :(得分:0)
如果您知道消息的长度是最大X字节,则可以使用以下内容:
package experiment;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class ProgramA {
public static void main(String[] args) {
try {
System.out.println("Started");
DatagramSocket datagramSocket = new DatagramSocket();
String message = "tokenasdfasdfasdfasdf";
InetAddress addr = InetAddress.getByName("localhost");
DatagramPacket datagramLength = new DatagramPacket(new byte[]{(byte)message.length()}, 1, addr, 5556);
DatagramPacket datagram = new DatagramPacket(message.getBytes(),message.getBytes().length, addr, 5556);
datagramSocket.send(datagramLength);
datagramSocket.send(datagram);
datagramSocket.close();
System.out.println("Done");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
package experiment;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
public class ProgramB {
public static void main(String[] args) {
try {
InetSocketAddress addr = new InetSocketAddress("localhost", 5556);
DatagramSocket datagramSocket = new DatagramSocket(addr);
byte[] messageLength = new byte[1];
DatagramPacket datagramLength = new DatagramPacket(messageLength, 1);
datagramSocket.receive(datagramLength);
byte[] message = new byte[(int)messageLength[0]];
DatagramPacket datagram = new DatagramPacket(message, message.length);
datagramSocket.receive(datagram);
datagramSocket.close();
for(int i = 0; i < message.length; i++) {
System.out.print((char)message[i]);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
这项工作假设消息的长度不超过127;否则,带有消息长度的datagramPacket必须包含多个字节