我怎么能以二进制形式在一个Java套接字发送数据? [英] How can I send data in binary form over a Java socket?

查看:161
本文介绍了我怎么能以二进制形式在一个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套接字库。我发现了Netty(从JBoss的),是很容易实现,真正强大。在Netty的ChannelBuffer类带有选项一大堆写不同的数据类型,当然,以可以编写自己的EN codeRS和去codeRS,如果你希望写的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.

这页是一个很好的起动 - 我能够做出一个相当复杂的客户端/服务器的自定义连接codeRS和去codeRS在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);

我希望这是有益的。

I hope that's useful.

这篇关于我怎么能以二进制形式在一个Java套接字发送数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆