如何在java中通过UDP发送int

我正在尝试编写一些通过UDP发送单个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”,这显然是不对的。我认为问题可能是我以某种方式将其作为字符串或其他东西发送而且它没有正确读取它。有帮助吗?     
已邀请:
使用数据流,如:
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);
    }
}     
InputStream.read()返回单个字节,而不是32位整数(请参阅javadoc)。所以你想要的是
ObjectInputStream os = new ObjectInputStream(bin);
os.readInt();
    
问题是你收到的CHAR码为'2'而不是acctual 2为整数。尝试将您的接收器代码更改为:
    DatagramSocket socket = new DatagramSocket(1989);
    DatagramPacket packet = new DatagramPacket(new byte[256] , 256);

    socket.receive(packet);

    System.out.print(new String(packet.getData()));
但是我想,ObjectInputStream解决方案对你来说会更好。     

要回复问题请先登录注册