5

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?

1
  • Are you sure the C program and the Java program treat binary ints and strings the same way? If you're not, send them as plain old text. If you don't have control of the C program reading the socket then you'll have no choice but to send the data in whatever format it is the C program wants. Commented Oct 5, 2010 at 16:16

3 Answers 3

10

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.

Sign up to request clarification or add additional context in comments.

Comments

6

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.

2 Comments

DataOutputStream seems to work just fine. My workday is over, I'll get back on this tomorrow.
Be aware that the link to this tutorial is for the JBoss version of Netty. That doesn't match the API of the netty.io download that the tutorial links to. Use netty.io/wiki/user-guide-for-4.x.html instead
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.