問題描述
我見過很多通過 Java 套接字發送序列化數據的示例,但我只想發送一些簡單的整數和字符串.而且,問題是我正在嘗試將這些信息傳達給用 C 編寫的二進制文件.
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.
那么,底線是:我怎樣才能在 Java 中通過套接字發送一些字節?
So, bottom line: how can I just send some bytes over a socket in Java?
推薦答案
我真的不建議直接使用 Java Sockets 庫.我發現 Netty(來自 JBoss)非常容易實現并且非常強大.Netty ChannelBuffer 類提供了許多用于編寫不同數據類型的選項,當然,如果您愿意,還可以編寫自己的編碼器和解碼器來將 POJO 寫入流中.
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.
這個頁面是一個非常好的入門 - 我能夠在 30 分鐘內使用自定義編碼器和解碼器制作一個相當復雜的客戶端/服務器:http://docs.jboss.org/netty/3.2/guide/html/start.html.
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.
如果你真的想使用 Java 套接字.套接字輸出流可以包裝在 DataOutputStream 中,它還允許您編寫許多不同的數據類型,例如:
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);
希望對你有用.
這篇關于如何通過 Java 套接字以二進制形式發送數據?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!