我在嘗試編寫一些通過UDP發送單個int的代碼。該代碼我到目前爲止有:如何在java中通過UDP發送int int
發件人:
int num = 2;
DatagramSocket socket = new DatagramSocket();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
PrintStream pout = new PrintStream(bout);
pout.print(num);
byte[] barray = bout.toByteArray();
DatagramPacket packet = new DatagramPacket(barray, barray.length);
InetAddress remote_addr = InetAddress.getByName("localhost");
packet.setAddress(remote_addr);
packet.setPort(1989);
socket.send(packet);
接收機:
DatagramSocket socket = new DatagramSocket(1989);
DatagramPacket packet = new DatagramPacket(new byte[256] , 256);
socket.receive(packet);
ByteArrayInputStream bin = new ByteArrayInputStream(packet.getData());
for (int i=0; i< packet.getLength(); i++)
{
int data = bin.read();
if(data == -1)
break;
else
System.out.print((int) data);
的問題是接收器打印 '50' 到屏幕這顯然是不對的。我認爲問題可能是我以某種方式將它作爲字符串或其他東西發送,而不是正確讀取它。任何幫助?