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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3864959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:45:08  来源:igfitidea点击:

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

javasocketsbinary

提问by evilpenguin

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. And, the problem is I'm trying to communicate these to a binary written in C.

我已经看到很多在 Java 中通过套接字发送序列化数据的例子,但我想要的只是发送一些简单的整数和一个字符串。而且,问题是我试图将这些与用 C 编写的二进制文件进行通信。

So, bottom line: how can I just send some bytes over a socket in Java?

所以,最重要的是:我怎样才能通过 Java 中的套接字发送一些字节?

采纳答案by alpian

I would really recommend not using the Java Sockets library directly. I've found Netty (from JBoss) to be really easy to implement and really powerful. 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.

我真的建议不要直接使用 Java Sockets 库。我发现 Netty(来自 JBoss)非常容易实现并且非常强大。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. The socket output stream can be wrapped in a DataOutputStream which allows you to write many different data types as well, for example:

如果你真的想使用 Java 套接字。套接字输出流可以包装在 DataOutputStream 中,它也允许您编写许多不同的数据类型,例如:

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

I hope that's useful.

我希望这很有用。

回答by Colin Hebert

You can use the simple OutputStreamgiven by the Socket.
From there you can writebytes.

您可以使用Socket提供的简单OutputStream。 从那里你可以字节。

If you want you can also encapsulate this stream in a BufferedOutputStreamto have a buffer.

如果需要,您还可以将此流封装在BufferedOutputStream 中以获得缓冲区。

回答by Joshua

I would recommend looking into Protocol Buffersfor the serialization and ZeroMQfor the data transfer.

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