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”,这显然是不正确的。我认为问题可能是我以某种方式将它作为字符串或其他东西发送,但它读取不正确。有什么帮助吗?
I'm trying to write a bit of code which sends a single int over UDP. The code I have so far:
Sender:
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 the receiver is printing '50' to screen which is obviously not right. I think that the problem may be that I'm somehow sending it as a string or something and its not reading it right. Any help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用数据流,例如:
}
Use data streams like:
}
InputStream.read() 返回单个字节,而不是 32 位整数(请参阅 javadoc)。所以你想要的是
InputStream.read() returns a single byte, not a 32-bit integer (see javadoc). So what you want is
问题是您收到的是“2”的字符代码,而不是实际的 2 作为整数。尝试将您的接收器代码更改为:
但我猜 ObjectInputStream 解决方案更适合您。
The problem is that you're receiving CHAR CODE of '2' and not acctual 2 as integer. Try changing the your receiver code to:
But ObjectInputStream solution would work better for you I guess.