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

How can I send data in binary form over a Java socket?(如何通过 Java 套接字以二进制形式发送数据?)
本文介绍了如何通过 Java 套接字以二进制形式发送数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我见过很多通过 Java 套接字发送序列化数据的示例,但我只想发送一些简单的整数和字符串.而且,问题是我正在尝试将这些信息传达给用 C 编写的二进制文件.

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 中通过套接字发送一些字节?

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

推荐答案

我真的不建议直接使用 Java Sockets 库.我发现 Netty(来自 JBoss)非常容易实现并且非常强大.Netty ChannelBuffer 类提供了许多用于编写不同数据类型的选项,当然,如果您愿意,还可以编写自己的编码器和解码器来将 POJO 写入流中.

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.

这个页面是一个非常好的入门 - 我能够在 30 分钟内使用自定义编码器和解码器制作一个相当复杂的客户端/服务器:http://docs.jboss.org/netty/3.2/guide/html/start.html.

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.

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

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:

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

希望对你有用.

这篇关于如何通过 Java 套接字以二进制形式发送数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)