Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 983
evilpenguin Avatar asked Oct 05 '10 15:10

evilpenguin


3 Answers

I would recommend looking into Protocol Buffers for the serialization and ZeroMQ for the data transfer.

like image 29
Joshua Avatar answered Sep 23 '22 00:09

Joshua


You can use the simple OutputStream given by the Socket.
From there you can write bytes.

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

like image 82
Colin Hebert Avatar answered Sep 23 '22 00:09

Colin Hebert


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.

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.

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.

like image 22
alpian Avatar answered Sep 25 '22 00:09

alpian