views:

69

answers:

3

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?

+5  A: 

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.

Colin Hebert
+3  A: 

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.

alpian
DataOutputStream seems to work just fine. My workday is over, I'll get back on this tomorrow.
evilpenguin
+1  A: 

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

Joshua