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

后端 未结 3 1858
感情败类
感情败类 2020-12-18 06:46

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

相关标签:
3条回答
  • 2020-12-18 07:03

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

    0 讨论(0)
  • 2020-12-18 07:19

    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.

    0 讨论(0)
  • 2020-12-18 07:21

    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.

    0 讨论(0)
提交回复
热议问题