How to send int through UDP in Java
•
Java
I'm trying to write some code to send a single int through UDP My code so far:
From:
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 );
receiver:
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);
The problem is that the receiver is printing "50" to the screen, which is obviously wrong I think the problem may be that I sent it as a string or something in some way and it didn't read it correctly Does it help?
Solution
Use data flow, such as:
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
final ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
final DataOutputStream dataOut = new DataOutputStream(byteOut);
dataOut.writeInt(1);
dataOut.writeDouble(1.2);
dataOut.writeLong(4l);
dataOut.close(); // or dataOut.flush()
final byte[] bytes = byteOut.toByteArray();
final ByteArrayInputStream byteIn = new ByteArrayInputStream(bytes);
final DataInputStream dataIn = new DataInputStream(byteIn);
final int integ = dataIn.readInt();
final double doub = dataIn.readDouble();
final long lon = dataIn.readLong();
System.out.println(integ);
System.out.println(doub);
System.out.println(lon);
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
