简体   繁体   English

如何通过Java套接字以二进制形式发送数据?

[英]How can I send data in binary form over a Java socket?

I've seen lots of examples of sending serialized data over sockets in Java, but all I want is to send some simple integers and a string. 我已经看到很多在Java中通过套接字发送序列化数据的例子,但我想要的只是发送一些简单的整数和一个字符串。 And, the problem is I'm trying to communicate these to a binary written in C. 而且,问题是我正在尝试将这些传达给用C编写的二进制文件。

So, bottom line: how can I just send some bytes over a socket in Java? 那么,底线:如何在Java中通过套接字发送一些字节?

You can use the simple OutputStream given by the Socket . 您可以使用Socket给出的简单OutputStream
From there you can write bytes. 从那里你可以字节。

If you want you can also encapsulate this stream in a BufferedOutputStream to have a buffer. 如果需要,还可以将此流封装在BufferedOutputStream中以获得缓冲区。

I would really recommend not using the Java Sockets library directly. 我真的建议不要直接使用Java套接字库。 I've found Netty (from JBoss) to be really easy to implement and really powerful. 我发现Netty(来自JBoss)非常容易实现并且非常强大。 The Netty ChannelBuffer class comes with a whole host of options for writing different data types and of course to can write your own encoders and decoders to write POJOs down the stream if you wish. Netty ChannelBuffer类提供了大量用于编写不同数据类型的选项,当然,如果您愿意,可以编写自己的编码器和解码器以在流中编写POJO。

This page is a really good starter - I was able to make a fairly sophisticated client/server with custom encoders and decoders in under 30 minutes reading this: http://docs.jboss.org/netty/3.2/guide/html/start.html . 这个页面是一个非常好的入门者 - 我能够在30分钟内用自定义编码器和解码器制作一个相当复杂的客户端/服务器: http//docs.jboss.org/netty/3.2/guide/html/start .html

If you really want to use Java sockets. 如果你真的想使用Java套接字。 The socket output stream can be wrapped in a DataOutputStream which allows you to write many different data types as well, for example: 套接字输出流可以包装在DataOutputStream中,它允许您编写许多不同的数据类型,例如:

new DataOutputStream(socket.getOutputStream()).writeInt(5);

I hope that's useful. 我希望这很有用。

我建议查看协议缓冲区的序列化和ZeroMQ的数据传输。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM