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

I have seen many examples of sending serialized data over sockets in Java, but all I want to do is send a few simple integers and a string. And the problem is that I am trying to transfer them to a binary file written in C.

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

+5
source share
3 answers

I would not recommend using the Java Sockets library directly. I found Netty (from JBoss) very easy to use and really powerful. The Netty ChannelBuffer class comes with many options for writing different types of data and, of course, for writing your own encoders and decoders for writing POJOs over the stream, if you want.

This page is a really good starter - I was able to make a rather complex client / server with custom encoders and decoders in less than 30 minutes by reading this: http://docs.jboss.org/netty/3.2/guide/html/start.html .

If you really want to use Java sockets. The output stream of the socket can be wrapped in a DataOutputStream, which also allows you to write many different types of data, for example:

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

I hope this is helpful.

+4

I would recommend studying Protocol Buffers for serialization and ZeroMQ for data transfer.

+1
source

All Articles